解释
wait/notify必须配合synchronized使用
demo
class NotifyStop2 { private final Object lock = new Object(); public void add(String s) throws InterruptedException { Thread.sleep(1000); synchronized (lock) { System.out.println("add notify qian"); //唤醒其他线程,但是其他线程不能执行,因为lock这把锁,还是被我占用的 lock.notify(); System.out.println("add notify hou"); try { Thread.sleep(5000); System.out.println("add wait qian"); //释放lock锁,其他线程可以执行了【使用wait释放锁,或者方法执行完毕,也是释放锁】 lock.wait(); System.out.println("add wait hou"); } catch (InterruptedException e) { e.printStackTrace(); } } } public void get() throws InterruptedException { synchronized (lock) { try { System.out.println("get wait qian"); lock.wait(); System.out.println("get wait hou"); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("get notify qian"); lock.notify(); Thread.sleep(5000); System.out.println("get notify hou"); } } public static void main(String[] args) { NotifyStop2 notifyStop2 = new NotifyStop2(); //特别注意使用同一个对象进行调用 new Thread(() -> { try { notifyStop2.add("abc"); } catch (InterruptedException e) { e.printStackTrace(); } }, "t1").start(); new Thread(() -> { try { notifyStop2.get(); } catch (InterruptedException e) { e.printStackTrace(); } }, "t2").start(); } }