[size=medium]首先看下官方的解释:
void notify()
唤醒在此对象监视器上等待的单个线程。
void notifyAll()
唤醒在此对象监视器上等待的所有线程。
void wait()
导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
下面是一段实例:
[/size]
[size=medium]
[color=red]注意上面的 wait() 和 notify()/notifyAll() 必须在调用同一个实例对象的。
因为在统一实例对象之间这两个方法才是相关联的,wait()方法执行后,通过notify()/notifyAll()才能唤醒wait()方法。[/color][/size]
void notify()
唤醒在此对象监视器上等待的单个线程。
void notifyAll()
唤醒在此对象监视器上等待的所有线程。
void wait()
导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
下面是一段实例:
[/size]
public class OtherObject {
public synchronized void await(){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void anotify(){
notifyAll();
}
}
public class ShareDataThread implements Runnable{
private static String name;
/**
* wait()导致当前的线程等待,直到其他线程调用此对象(the same object
* like: OtherObject)的 notify() 方法或 notifyAll() 方法。
**/
private static OtherObject oo = new OtherObject();
@Override
public void run() {
name = "simon";
oo.anotify();
}
public static void main(String[] args){
Thread t = new Thread(new ShareDataThread());
t.start();
//method 1
/*try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}*/
//method 2
while(name == null){
System.out.println("before");
oo.await();
}
System.out.println(name);
}
}
[size=medium]
[color=red]注意上面的 wait() 和 notify()/notifyAll() 必须在调用同一个实例对象的。
因为在统一实例对象之间这两个方法才是相关联的,wait()方法执行后,通过notify()/notifyAll()才能唤醒wait()方法。[/color][/size]