- 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);
- }
- }
- }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。