Java线程中的wait, notify and notifyAll
Object对象中有wait, notify and notifyAll三个方法,其主要用来进行进程间的通讯(communicate about their locking status)。需要注意的是,这这些方法需要在同步块中调用。
wait
wait有三个重载方法,一个是一直等待,直到另一线程调用该对象上的notify() 或 notifyAll()方法来唤醒该线程,另外两个是让调用wait()的线程等待指定的时间后自动唤醒或者在此之前被另一线程的notify() 或 notifyAll()唤醒。调用wait()方法后,该线程释放了该对象上的monitor。
notify
notify()只能唤醒等待在该对象上的一个线程,唤醒后,该线程开始执行,如果有多个线程等待在该对象上,那么notify()只能唤醒其中一个。具体唤醒哪一个,依赖于OS对线程管理的实现。
notifyAll
唤醒所有等待在该对象上的线程,具体哪一个线程先进入Running状态,依赖于OS对线程管理的实现。
package Test;
/** * Created by siege on 2015-09-14. */
public class Message {
private String msg;
public Message(String str){
this.msg=str;
}
public String getMsg() {
return msg;
}
public void setMsg(String str) {
this.msg=str;
}
}
package Test;
/** * Created by siege on 2015-09-14. */
public class Waiter implements Runnable {
private Message msg;
public Waiter(Message msg) {
this.msg = msg;
}
@Override
public void run() {
String name=Thread.currentThread().getName();
synchronized (msg){
try {
System.out.println(name+" waiting to get notified at time:"+System.currentTimeMillis());
msg.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+" waiter thread got notified at time:"+System.currentTimeMillis());
System.out.println(name+" processed: "+msg.getMsg());
}
}
}
package Test;
/** * Created by siege on 2015-09-14. */
public class Notifier implements Runnable {
private Message msg;
public Notifier(Message msg) {
this.msg = msg;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name+" started");
try {
Thread.sleep(1000);
synchronized (msg){
msg.setMsg(name+" Notifier work done");
msg.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package Test;
/** * Created by siege on 2015-09-14. */
public class WaitNotifyTest {
public static void main(String[] args) {
Message msg=new Message("process it");
Waiter waiter=new Waiter(msg);
new Thread(waiter,"waiter").start();
Waiter waiter1=new Waiter(msg);
new Thread(waiter1,"waiter1").start();
Notifier notifier=new Notifier(msg);
new Thread(notifier,"notifier").start();
System.out.println("All the threads are started");
}
}
输出结果可能如下所示:
All the threads are started waiter waiting to get notified at time:1442232184486 waiter1 waiting to get notified at time:1442232184486 notifier started waiter waiter thread got notified at time:1442232185495 waiter processed: notifier Notifier work done