美文网首页
奇偶线程交替打印1到100的数字

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

作者: 多彩海洋 | 来源:发表于2019-09-24 11:39 被阅读0次
  • 主要使用同步锁和notifyall(),wait()
  • 注意逻辑顺序,先唤醒其他线程,再释放锁
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();
                    }
                }
            }
        }
    }
}

相关文章

网友评论

      本文标题:奇偶线程交替打印1到100的数字

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