等待与通知
public final void wait() throws InterruptedException;
public final native void notify();
public final native void notifyAll();
obj.wait()唤醒条件
- 其它线程调用了obj.notify();
- 其它线程调用了obj.notifyAll();
- wait(毫秒数)达到指定的时间后自然被激活
说明:在SUN Jdk中,object.wait()还有可能被假唤醒,因此在object.wait被唤醒后应再次确认需要等待的状态是否变更了,如果未变更则继续进入wait状态,这种做法通称为double check
中断响应
wait方法支持响应中断
public final void wait() throws InterruptedException {
wait(0);
}
public final native void wait(long timeout) throws InterruptedException;
示例:
public class Appliction {
private static Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
synchronized (lock){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.err.println(Thread.currentThread().getName() + " canceled===>");
});
thread.start();
TimeUnit.SECONDS.sleep(3);
thread.interrupt();
System.err.println(Thread.currentThread().getName() + " finished===>");
}
}
知识点
- wait()方法在执行后会释放监视锁
- Object.wait()与Thread.sleep()方法的主要区别是wait()方法会释放目标对象的监视锁,而sleep()方法不会释放任何资源