保护性暂停,用在一个线程等待另一个线程的执行结果。JDK 中,join 的实现、Future 的实现,采用的就是此模式。
class GuardedObject{ private final Object lock=new Object(); private Object response; public Object get() throws Exception{ synchronized (lock){ while (response==null){ lock.wait(); } return response; } } public Object get(long timeout) throws Exception{ synchronized (lock){ long start=System.currentTimeMillis(); long duration=0L; while (response==null){ timeout=timeout-duration; if(timeout<=0){ break; } lock.wait(timeout); duration=System.currentTimeMillis()-start; } return response; } } public void complate(){ synchronized (lock){ if (response==null){ response=new Object(); } lock.notifyAll(); } } }
join原理
public final void join() throws InterruptedException { join(0); }public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }
调用者轮询检查线程 alive 状态,join 体现的是保护性暂停模式。