交替打印奇偶数

2019-09-26  本文已影响0人  天堂鸟6

public class PrintNumber {

private static volatile int i = 0;

public static void main(String[] args) throws Exception {
    final Object obj = new Object();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            synchronized (obj) {
                for (; i < 100; ) {
                    System.out.println(Thread.currentThread().getName() + " " + (i++));
                    try {
                        obj.notifyAll();
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                obj.notifyAll();
            }
        }
    };

    Thread t1 = new Thread(runnable, "线程1 ");
    Thread t2 = new Thread(runnable, "线程2 ");
    t2.start();
    t1.start();
}

}

上一篇下一篇

猜你喜欢

热点阅读