小渣飞、
2020-11-11 02:21
采纳率: 90.3%
浏览 53
已结题

这段 Java 代码的线程锁对象为 final 的,为何只有一个线程会被执行?

 

  • public class WindowTestThree {
        public static void main(String[] args) {
            WindowThree w = new WindowThree();
            Thread w1 = new Thread(w);
            Thread w2 = new Thread(w);
            Thread w3 = new Thread(w);
            w1.start();
            w2.start();
            w3.start();
        }
    }
    
    class WindowThree implements Runnable {
        // private static int ticket = 100;
        private int ticket = 100;
        // final Object obj = new Object();
        Object obj = new Object();
    
        @Override
        public void run() {
            while (true) {
                synchronized (obj) {
                    if (ticket > 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + ":成功售出一张票,剩余" + ticket + "张票");
                        ticket--;
                    } else {
                        break;
                    }
                }
            }
        }
    }

     

2条回答 默认 最新

相关推荐 更多相似问题