notify通知的遗漏很容易理解,即threadA还没开始wait的时候,threadB已经notify了,这样,threadB通知是没有任何响应的,当threadB退出synchronized代码块后,threadA再开始wait,便会一直阻塞等待,直到被别的线程打断。
遗漏通知的代码
下面给出一段代码演示通知是如何遗漏的,如下:
public class MissedNotify extends Object {private Object proceedLock;public MissedNotify() {print("in MissedNotify()");proceedLock = new Object();}public void waitToProceed() throws InterruptedException {print("in waitToProceed() - entered");synchronized ( proceedLock ) {print("in waitToProceed() - about to wait()");proceedLock.wait();print("in waitToProceed() - back from wait()");}print("in waitToProceed() - leaving");}public void proceed() {print("in proceed() - entered");synchronized ( proceedLock ) {print("in proceed() - about to notifyAll()");proceedLock.notifyAll();print("in proceed() - back from notifyAll()");}print("in proceed() - leaving");}private static void print(String msg) {String name = Thread.currentThread().getName();System.out.println(name + ": " + msg);}public static void main(String[] args) {final MissedNotify mn = new MissedNotify();Runnable runA = new Runnable() {public void run() {try {//休眠1000ms,大于runB中的500ms,//是为了后调用waitToProceed,从而先notifyAll,后wait,//从而造成通知的遗漏Thread.sleep(1000);mn.waitToProceed();} catch ( InterruptedException x ) {x.printStackTrace();}}};Thread threadA = new Thread(runA, "threadA");threadA.start();Runnable runB = new Runnable() {public void run() {try {//休眠500ms,小于runA中的1000ms,//是为了先调用proceed,从而先notifyAll,后wait,//从而造成通知的遗漏Thread.sleep(500);mn.proceed();} catch ( InterruptedException x ) {x.printStackTrace();}}};Thread threadB = new Thread(runB, "threadB");threadB.start();try { Thread.sleep(10000);} catch ( InterruptedException x ) {}//试图打断wait阻塞print("about to invoke interrupt() on threadA");threadA.interrupt();}}
执行结果如下:
分析:由于threadB在执行mn.proceed()之前只休眠了500ms,而threadA在执行mn.waitToProceed()之前休眠了1000ms,因此,threadB会先苏醒,继而执行mn.proceed(),获取到proceedLock的对象锁,继而执行其中的notifyAll(),当退出proceed()方法中的synchronized代码块时,threadA才有机会获取proceedLock的对象锁,继而执行其中的wait()方法,但此时notifyAll()方法已经执行完毕,threadA便漏掉了threadB的通知,便会阻塞下去。后面主线程休眠10秒后,尝试中断threadA线程,使其抛出InterruptedException。
修正后的代码
为了修正MissedNotify,需要添加一个boolean指示变量,该变量只能在同步代码块内部访问和修改。修改后的代码如下:
public class MissedNotifyFix extends Object {private Object proceedLock;//该标志位用来指示线程是否需要等待private boolean okToProceed;public MissedNotifyFix() {print("in MissedNotify()");proceedLock = new Object();//先设置为falseokToProceed = false;}public void waitToProceed() throws InterruptedException {print("in waitToProceed() - entered");synchronized ( proceedLock ) {print("in waitToProceed() - entered sync block");//while循环判断,这里不用if的原因是为了防止早期通知while ( okToProceed == false ) {print("in waitToProceed() - about to wait()");proceedLock.wait();print("in waitToProceed() - back from wait()");}print("in waitToProceed() - leaving sync block");}print("in waitToProceed() - leaving");}public void proceed() {print("in proceed() - entered");synchronized ( proceedLock ) {print("in proceed() - entered sync block");//通知之前,将其设置为true,这样即使出现通知遗漏的情况,也不会使线程在wait出阻塞okToProceed = true;print("in proceed() - changed okToProceed to true");proceedLock.notifyAll();print("in proceed() - just did notifyAll()");print("in proceed() - leaving sync block");}print("in proceed() - leaving");}private static void print(String msg) {String name = Thread.currentThread().getName();System.out.println(name + ": " + msg);}public static void main(String[] args) {final MissedNotifyFix mnf = new MissedNotifyFix();Runnable runA = new Runnable() {public void run() {try {//休眠1000ms,大于runB中的500ms,//是为了后调用waitToProceed,从而先notifyAll,后wait,Thread.sleep(1000);mnf.waitToProceed();} catch ( InterruptedException x ) {x.printStackTrace();}}};Thread threadA = new Thread(runA, "threadA");threadA.start();Runnable runB = new Runnable() {public void run() {try {//休眠500ms,小于runA中的1000ms,//是为了先调用proceed,从而先notifyAll,后wait,Thread.sleep(500);mnf.proceed();} catch ( InterruptedException x ) {x.printStackTrace();}}};Thread threadB = new Thread(runB, "threadB");threadB.start();try { Thread.sleep(10000);} catch ( InterruptedException x ) {}print("about to invoke interrupt() on threadA");threadA.interrupt();}}
执行结果如下:
注意代码中加了注释的部分,在threadB进行通知之前,先将okToProceed置为true,这样如果threadA将通知遗漏,那么就不会进入while循环,也便不会执行wait方法,线程也就不会阻塞。如果通知没有被遗漏,wait方法返回后,okToProceed已经被置为true,下次while循环判断条件不成立,便会退出循环。
这样,通过标志位和wait、notifyAll的配合使用,便避免了通知遗漏而造成的阻塞问题。
总结:在使用线程的等待/通知机制时,一般都要配合一个boolean变量值(或者其他能够判断真假的条件),在notify之前改变该boolean变量的值,让wait返回后能够退出while循环(一般都要在wait方法外围加一层while循环,以防止早期通知),或在通知被遗漏后,不会被阻塞在wait方法处。这样便保证了程序的正确性。
如果线程在等待时接到通知,但线程等待的条件还不满足,此时,线程接到的就是早期通知,如果条件满足的时间很短,但很快又改变了,而变得不再满足,这时也将发生早期通知。这种现象听起来很奇怪,下面通过一个示例程序来说明问题。
很简单,两个线程等待删除List中的元素,同时另外一个线程正要向其中添加项目。代码如下:
import java.util.*;public class EarlyNotify extends Object {private List list;public EarlyNotify() {list = Collections.synchronizedList(new LinkedList());}public String removeItem() throws InterruptedException {print("in removeItem() - entering");synchronized ( list ) {if ( list.isEmpty() ) { //这里用if语句会发生危险print("in removeItem() - about to wait()");list.wait();print("in removeItem() - done with wait()");}//删除元素String item = (String) list.remove(0);print("in removeItem() - leaving");return item;}}public void addItem(String item) {print("in addItem() - entering");synchronized ( list ) {//添加元素list.add(item);print("in addItem() - just added: '" + item + "'");//添加后,通知所有线程list.notifyAll();print("in addItem() - just notified");}print("in addItem() - leaving");}private static void print(String msg) {String name = Thread.currentThread().getName();System.out.println(name + ": " + msg);}public static void main(String[] args) {final EarlyNotify en = new EarlyNotify();Runnable runA = new Runnable() {public void run() {try {String item = en.removeItem();print("in run() - returned: '" + item + "'");} catch ( InterruptedException ix ) {print("interrupted!");} catch ( Exception x ) {print("threw an Exception!!!\n" + x);}}};Runnable runB = new Runnable() {public void run() {en.addItem("Hello!");}};try {//启动第一个删除元素的线程Thread threadA1 = new Thread(runA, "threadA1");threadA1.start();Thread.sleep(500);//启动第二个删除元素的线程Thread threadA2 = new Thread(runA, "threadA2");threadA2.start();Thread.sleep(500);//启动增加元素的线程Thread threadB = new Thread(runB, "threadB");threadB.start();Thread.sleep(10000); // wait 10 secondsthreadA1.interrupt();threadA2.interrupt();} catch ( InterruptedException x ) {}}}
执行结果如下:
分析:首先启动threadA1,threadA1在removeItem()中调用wait(),从而释放list上的对象锁。再过500ms,启动threadA2,threadA2调用removeItem(),获取list上的对象锁,也发现列表为空,从而在wait()方法处阻塞,释放list上的对象锁。再过500ms后,启动threadB,并调用addItem,获得list上的对象锁,并在list中添加一个元素,同时用notifyAll通知所有线程。
threadA1和threadA2都从wait()返回,等待获取list对象上的对象锁,并试图从列表中删除添加的元素,这就会产生麻烦,只有其中一个操作能成功。假设threadA1获取了list上的对象锁,并删除元素成功,在退出synchronized代码块时,它便会释放list上的对象锁,此时threadA2便会获取list上的对象锁,会继续删除list中的元素,但是list已经为空了,这便会抛出IndexOutOfBoundsException。
要避免以上问题只需将wait外围的if语句改为while循环即可,这样当list为空时,线程便会继续等待,而不会继续去执行删除list中元素的代码。
修改后的执行结果如下:
总结:在使用线程的等待/通知机制时,一般都要在while循环中调用wait()方法,满足条件时,才让while循环退出,这样一般也要配合使用一个boolean变量(或其他能判断真假的条件,如本文中的list.isEmpty()),满足while循环的条件时,进入while循环,执行wait()方法,不满足while循环的条件时,跳出循环,执行后面的代码。