经典

作者: couriravant | 来源:发表于2019-12-31 11:49 被阅读0次

    线程交替打印:

    private int count = 0;
    private final Object lock = new Object();
    
    public void turning() throws InterruptedException {
        new Thread(new TurningRunner(), "偶数").start();
        // 确保偶数线程线先获取到锁
        Thread.sleep(1);
        new Thread(new TurningRunner(), "奇数").start();
    }
    
    class TurningRunner implements Runnable {
      @Override
      public void run() {
          while (count <= 100) {
              // 获取锁
              synchronized (lock) {
                  // 拿到锁就打印
                  System.out.println(Thread.currentThread().getName() + ": " + count++);
                  // 唤醒其他线程
                  lock.notifyAll();
                  try {
                      if (count <= 100) {
                          // 如果任务还没有结束,则让出当前的锁并休眠
                          lock.wait();
                      }
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          }
      }
    }
    

    相关文章

      网友评论

          本文标题:经典

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