一个线程A调用了对象obj的wait方法进入等待,
另一个线程调用对象obj的notify()或者notifyAll()方法,
A在收到notify()或者notifyAll()后,返回,
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class WaitNotifyThread {
private static boolean flag=true;
private static Object obj=new Object();
private static DateFormat format=new SimpleDateFormat("HH:mm:ss");
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Thread wt=new Thread(new WaitThread(),"wt");
wt.start();
Thread.sleep(1);
Thread notifyThread=new Thread(new NotifyThread(),"notifyThread");
notifyThread.start();
}
public static class WaitThread implements Runnable{
public void run(){
synchronized(obj){
while(flag){
try{
System.out.println(Thread.currentThread().getName()+"flag is true, wait at "+format.format(new Date()));
obj.wait();
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"flag is false, wait at "+format.format(new Date()));
}
}
}
public static class NotifyThread implements Runnable{
public void run(){
synchronized(obj){
System.out.println(Thread.currentThread().getName()+"keep lock , notifyThread at "+format.format(new Date()));
obj.notifyAll();
flag=false;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//再次加锁
synchronized(obj){
System.out.println(Thread.currentThread().getName()+"keep lock again , notifyThread at "+format.format(new Date()));
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
运行结果为:
wtflag is true, wait at 00:54:51
notifyThreadkeep lock , notifyThread at 00:54:51
notifyThreadkeep lock again , notifyThread at 00:54:51
wtflag is false, wait at 00:54:51
wait方法就是使当前线程等待该对象的锁,当前线程必须是该对象的拥有者,也就是具有该对象的锁。wait()方法一直等待,直到获得锁或者被中断。wait(long timeout)设定一个超时间隔,如果在规定时间内没有获得锁就返回。
调用该方法后当前线程进入睡眠状态,直到以下事件发生。
(1)其他线程调用了该对象的notify方法。
(2)其他线程调用了该对象的notifyAll方法。
(3)其他线程调用了interrupt中断该线程。
(4)时间间隔到了。
此时该线程就可以被调度了,如果是被中断的话就抛出一个InterruptedException异常。