介绍 Object的 wait()和notify()用于线程间协作 wait()方法 当在一个对象实例上调用wait()方法后,当前线程就会在这个对象上等待 notify() 当object.notify()方法被调用时,就会从这个对象的等待队列中随机选择一个线程,并将其唤醒 notifyAll() 唤醒该对象的所有等待线程 wait()和notify()不能随便调用,必须包含在synchronized语句中,它们都需要先获取目标对象的监视器。 如果没有在synchronized语句中会报java.lang.IllegalMonitorStateException 另: wait()方法会释放目标对象的锁,而Thread.sleep()方法不会释放目标对象锁 调用wait()和notify()方法之前需要先获取对象的监视器
Demo
public class WaitAndNotify {
final static Object object = new Object();
public static class Test1 extends Thread{
@Override
public void run() {
synchronized (object){
System.out.println(System.currentTimeMillis()+":Test1 start!");
try {
System.out.println(System.currentTimeMillis()+":Test1 wait for object");
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()+":Test1 end!");
}
}
}
public static class Test2 extends Thread{
@Override
public void run() {
synchronized(object){
System.out.println(System.currentTimeMillis()+":Test2 start!notify one thread");
object.notify();
System.out.println(System.currentTimeMillis()+":Test2 end!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Test1().start();
new Test2().start();
}
}
结果
1588846940619:Test1 start!
1588846940619:Test1 wait for object
1588846940619:Test2 start!notify one thread
1588846940619:Test2 end!
1588846942620:Test1 end!
3万+



被折叠的 条评论
为什么被折叠?



