wait必须放在while循环里面的原因探析

先看一段代码:

    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 seconds  
      
                threadA1.interrupt();  
                threadA2.interrupt();  
            } catch ( InterruptedException x ) {}  
        }  
    }  

输出结果:
threadA1: in removeItem() - entering
threadA1: in removeItem() - about to wait()
threadA2: in removeItem() - entering
threadA2: in removeItem() - about to wait()
threadB: in addItem() - entering
threadB: in addItem() - just added: 'Hello!'
threadB: in addItem() - just notified
threadA2: in removeItem() - done with wait()
threadA2: in removeItem() - leaving
threadA2: in run() - returned: 'Hello!'
threadA1: in removeItem() - done with wait()
threadA1: threw an Exception!!!
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
threadB: in addItem() - leaving

原因分析:

首先启动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。

解决办法:

将if换为while。重新判断是否为空,为空时继续等待挂起。

放在while里面,是防止出于waiting的对象被别的原因调用了唤醒方法,但是while里面的条件并没有满足(也可能当时满足了,但是由于别的线程操作后,又不满足了),就需要再次调用wait将其挂起。

好笑的解释:

如果是两个狙击手,在同时等待一个人,第一个人先打死了(改变了某个状态,不满足了条件了),第二个人还要再开一枪?针对两个线程同时等待还是要加这个while的。

  • 17
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值