Thread-wait/notify
程序员文章站
2022-07-06 12:31:50
...
java 线程通过对象的Wait和Notify进行同步,但是存在一定的危险性
其重点是:wait 和 notify 的 时间点
举例:
package com.horizon.thread.aqs; public class NotSafeWaitNotify { private static StringBuffer lock = new StringBuffer(); public static void main(String[] args) throws Exception { // testWaitAfterNotify(); //testWaitBeforeNotify(); testWaitAfterNotifyV2(); } /** * 先notify 后wait,不能正常工作 */ private static void testWaitAfterNotify() throws Exception { Thread modifyThread = new Thread() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock) { lock.append("1000"); lock.notify(); } } }; modifyThread.start(); Thread.sleep(2000); synchronized (lock) { lock.wait(); } System.out.println(lock); } /** * 先notify 后wait,不能正常工作 * 改进思路:先判断是否已经有结果 */ private static void testWaitAfterNotifyV2() throws Exception { Thread modifyThread = new Thread() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock) { lock.append("1000"); lock.notify(); } } }; modifyThread.start(); Thread.sleep(2000); synchronized (lock) { //先判断是否已经有结果 if (lock.length() < 0) { lock.wait(); } } System.out.println(lock); } /** * 先wait 后notify,正常工作 */ private static void testWaitBeforeNotify() throws Exception { Thread modifyThread = new Thread() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock) { lock.append("1000"); lock.notify(); } } }; modifyThread.start(); synchronized (lock) { lock.wait(); } System.out.println(lock); } }
上一篇: 简直就是军大衣啊
下一篇: ES6 字符串扩展+正则扩展+数值扩展