notify()唤醒一个被挂起的线程,notifyAll唤醒所有被挂起的线程。
代码思想:实现一个计数器,当只剩一个线程没有被挂起时,一次性唤醒所有线程!
public class TestThread implements Runnable{ private Wait wait = new Wait(3); @Override public void run() { wait.does(); } public static void main(String[]args) { TestThread tt = new TestThread(); Thread a = new Thread(tt); Thread b = new Thread(tt); Thread c = new Thread(tt); Thread d = new Thread(tt); a.start();b.start();c.start();d.start(); } } class Wait{ private int counter;//剩余多少个线程未被挂起,当只剩下一个线程的时候,唤醒所有线程 private int wake = 0;//唤醒了多少个线程 public Wait(int counter) { this.counter = counter; } public synchronized void does() { if(counter>0) { System.out.println("wait"+counter); try { counter--;//逐个挂起线程 this.wait(); System.out.println(++wake); } catch (InterruptedException e) { e.printStackTrace(); } }else { this.notifyAll(); } } }
输出结果:
如果改成notify(),则只能唤醒一个线程,输出结果: