- public class Payment
- {
- public int sku = 100;
- public static void main(String[] args)
- {
- Payment p = new Payment();
- Order1 o1 = new Order1(p);
- Order2 o2 = new Order2(p);
- o1.start();
- o2.start();
- }
- }
- class Order1 extends Thread
- {
- Payment p;
- public Order1(Payment p)
- {
- this.p = p;
- }
- @Override
- public void run()//重写run()
- {
- synchronized(p) //对象p加锁
- {
- p.sku -= 1;
- System.out.println("剩余库存:" + p.sku);
- }
- }
- }
- class Order2 extends Thread
- {
- Payment p;
- public Order2(Payment p)
- {
- this.p = p;
- }
- @Override
- public void run()
- {
- synchronized(p)
- {
- p.sku -= 1;
- System.out.println("剩余库存:" + p.sku);
- }
- }
- }
本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1191880,如需转载请自行联系原作者