wait(),notify()和notifyAll()
他们都是java.lang.Object的方法:
- wait(): Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
- notify(): Wakes up a single thread that is waiting on this object's monitor.
- notifyAll(): Wakes up all threads that are waiting on this object's monitor.
wait()的使用方式:
synchronized( lockObject ) { while( ! condition ) { lockObject.wait(); } //take the action here; }
notify()的使用方式:
synchronized(lockObject) { //establish_the_condition; lockObject.notify(); //any additional code if needed }
都需要同步,但notify不用在循环里。
notifyAll()的使用方式:
synchronized(lockObject) { establish_the_condition; lockObject.notifyAll(); }
一般情况下使用notifyAll(),notify()较难掌控,容易出现想不到的问题。(牺牲性能,满足安全)
一个简单的例子,2对执行完5遍之后最终将有2个线程一直在waiting状态:
public class OutputThread1 { private static Object lock; public static void main(String[] args) { lock = new Object(); Thread1 thread1 = new Thread1(); Thread2 thread2 = new Thread2(); Thread3 thread3 = new Thread3(); Thread3 thread4 = new Thread3(); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } static class Thread1 extends Thread { @Override public void run() { synchronized (lock) { while (true) { try { lock.wait(); } catch (InterruptedException e) { } System.out .println("线程" + Thread.currentThread().getName() + ":" + "wait"); } } } } static class Thread2 extends Thread { @Override public void run() { synchronized (lock) { while (true) { try { lock.wait(); } catch (InterruptedException e) { } System.out .println("线程" + Thread.currentThread().getName() + ":" + "wait"); } } } } static class Thread3 extends Thread { @Override public void run() { for (int i = 0; i < 6; i++) { synchronized (lock) { try { Thread.sleep(100); lock.notifyAll(); } catch (Exception e) { } System.out.println( "线程" + Thread.currentThread().getName() + ":" + "notifyAll"); } } } } }