美文网首页
交替打印奇偶数

交替打印奇偶数

作者: 天堂鸟6 | 来源:发表于2019-09-26 14:44 被阅读0次

    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();
    }
    

    }

    相关文章

      网友评论

          本文标题:交替打印奇偶数

          本文链接:https://www.haomeiwen.com/subject/mcxnuctx.html