线程1----wait()
1 Object o=new Object(); 2 waitAndNotifyMap.put(urlId,o); 3 System.out.println(urlId+"运行到阻塞"); 4 synchronized (o){ 5 o.wait(1000); 6 }
线程2----notify()
1 if(waitAndNotifyMap.get(pid)==null) { 2 //如果待唤醒的父线程的锁对象还没有加入map就先睡0.5s 3 System.out.println(urlId+"父锁"+pid+"还未设置,等待"); 4 TimeUnit.MILLISECONDS.sleep(500); 5 } 6 Object o=waitAndNotifyMap.get(pid); 7 synchronized (o){ 8 System.out.println(urlId+"唤醒"+pid); 9 o.notify(); 10 }
问题:
线程1运行到第3行,线程2运行到了第7行,此时Object已经被创建到map中,但是线程1还没有wait(),如果CPU时间继续分配给线程2,就会提前notify(),导致线程1超时等待1s后再执行,而不是被通知执行
标签:Object,pid,调度,System,线程,notify,urlId,有趣,多线程 From: https://www.cnblogs.com/JNU-Iot-Longxin/p/16636679.html