用wait和notify /** * 两个线程交替打印0~100的寄偶数,用wait和notify */ public class WaitNotifyPrintOddEvenWait { private static int count = 0; private static final Object lock = new Object(); public static void main(String[] args) { new Thread(new TurningRunner(),"偶数").start(); new Thread(new TurningRunner(),"奇数").start(); } //1.拿到锁,我们就打印 //2。一旦打印完唤醒其他线程就休眠 static class TurningRunner implements Runnable{ @Override public void run() { while (count <= 100) { synchronized (lock){ System.out.println(Thread.currentThread().getName()+";"+ count++); lock.notify(); if(count<=100){ try { //如果任务没结束,唤醒其他线程,自己休眠 lock.wait();