ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### 等待与通知 wait方法的语义有两个,一个是释放当前的对象锁、另一个是使得当前线程进入阻塞队列, 而这些操作都和监视器是相关的,所以wait必须要获得一个监视器锁 ``` 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 ![](https://img.kancloud.cn/7b/04/7b04c75e76f112dd968991e1b4ebb4cd_1790x332.png) ### 中断响应 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\(\)方法不会释放任何资源