wait和notify是Object的方法,前者用于让运行的线程阻塞进入TIMED_WAITING模式,后者用于通知相同锁对象阻塞的线程继续运行。
一般地使用模式为:
Object lock = new Object();
function1(){
syncronized(lock){
while(条件不满足){
lock.wait();
}
TODO other things...
}
}
function2(){
syncronized(lock){
lock.notify();
//lock.notifyAll();
}
}
保护性暂停模式即可以使用这种方式实现。保护性暂停即是说一个线程要拿到结果,需要等待另外的线程。
我们可以设计一个同步类。
class GuardObject{
Object lock = new Object();
Object result = null;
pubblic Object get(){
syncronized(this){
while(null == result){
wait();
}
return result;
}
}
public void complete(Object result){
syncronized(this){
this.result=result;
notify();
//notifyAll();
}
}
}
当结果还没有的时候,get方法所在线程就一直等待,直到另外的线程得到结果后通知。
更进一步的,get()方法可以设置超时时间。Thread类的join方法也类似这种模式。
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;
}
}
}