奇偶线程交替打印1到100的数字

2019-09-24  本文已影响0人  多彩海洋
public class TurningTest {
   private int count =0;
   private final Object lock = new Object();

    public static void main(String[] args) {
        new TurningTest().foo();
    }

    public void foo(){
        new Thread(new myRun(),"偶线程").start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(new myRun(),"奇线程").start();
    }

    class myRun implements Runnable{
        @Override
        public void run(){
            while (count<=100){
                synchronized (lock){
                    System.out.println(Thread.currentThread().getName()+": "+count);
                    count++;
                    lock.notifyAll();
                    try {
                        if(count<=100){
                            lock.wait();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读