wait、notify和notify是Object类的3个final方法,这三个方法可以实现线程间的通信。在线程中调用Object的wait方法,将阻塞当前线程等待其它线程的通知,通知使用notify或notifyAll方法。当其它线程中调用了Object的notify或notifyAll方法后,将通知调用wait方法的线程继续执行wait后的代码。
下边的例子有两个waiter和一个notifier,waiter先输出message的content,然后调用message的wait方法阻塞当前线程,然后notifer被调用,修改message的content,再调用notify或notifyAll方法,此时waiter被唤醒,输出notifer修改后的message content。
class Message {
private String content;
public Message(String content) {
this.content = content;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return this.content;
}
}
class Waiter implements Runnable {
private Message message;
public Waiter(Message message) {
this.message = message;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
synchronized(message) {
System.out.println(threadName + "输出message.content:" + message.getContent());
System.out.println(threadName + "正在运行,现在执行wait方法。");
try {
message.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadName + "被重新唤醒,继续执行。");
System.out.println(threadName + "输出message.content:" + message.getContent());
System.out.println(threadName + "执行完成!");
}
}
}
class Notifier implements Runnable {
private Message message;
public Notifier(Message message) {
this.message = message;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + "正在运行,等待执行notify/notifyAll方法。");
synchronized(message) {
message.setContent(threadName + "修改了content");
System.out.println(threadName + "执行notify方法");
//message.notify(); //调用notify(),只有一个waiter会被唤醒然后执行完成。
message.notifyAll(); //所有waiter都会被唤醒并执行完成。
}
}
}
public class WaitAndNotifyDemo {
public static void main(String[] args) {
Message message = new Message("一个新的Message");
Waiter w1 = new Waiter(message);
new Thread(w1, "waiter1").start();
Waiter w2 = new Waiter(message);
new Thread(w2, "waiter2").start();
Notifier n1 = new Notifier(message);
new Thread(n1, "notifier1").start();
}
}