使用notify()和notifyAll()在代码中不起作用
我粘贴了下面的代码.这已经足够评论了.
清除wait().来到这里时它跳到另一个街区.那部分我是橡木的. 我怀疑的是为什么我们使用notify和notifyAll().如果从下面的代码中删除这两个,它可以正常工作. class Reader extends Thread{ Calculator c; //here we didn't write no-arg constructor. Note this. // one - arg constructor. public Reader(Calculator calc){ c = calc; } public void run(){ synchronized(c){ // 2. Acquiring the object lock and executes this code of block. try{ System.out.println("Waiting for calculation..."); c.wait(); // 3. Release the object lock and moves to the second synchronize block below // 6. Later the object get the lock here and moves on. }catch(InterruptedException e){ } System.out.println("Total is: "+c.total); } } public static void main(String[] args){ //Instantiating new with no-arg. One more doubt,How this work without no-arg constructor above. Please explain. Calculator calculator = new Calculator(); //Instantiating new with one-arg new Reader(calculator).start(); new Reader(calculator).start(); new Reader(calculator).start(); // 1. Once you start here it will goto first synchronized code block above calculator.start(); } } class Calculator extends Thread{ int total; public void run(){ synchronized(this){ // 4. This block acquires that object lock and executes the code block below. for(int i=0;i<100;i++){ total +=i; } // 5. As per documentation,If we give notify() it will release the object lock to only one thread object of its choice. // If we use notifyAll(); it will release the object lock to all the three thread object. notify(); // My doubt here is without using the notify or notifyAll it is working fine. // As per docs if we use notify() only one object should get the lock. That is also not working here. } } } 解决方法
一般评论:
the javadoc of
Object#wait 表示
因此,等待线程可以在不通知的情况下唤醒,并且您的设计应该通过在循环中等待并检查退出条件(参见javadoc中的示例)来考虑这一点. 但是,在您的情况下,问题略有不同.根据
因此,当您的计算器完成时,它会调用this.notifyAll()并唤醒所有等待的线程. 怎么解决? 你应该使用一个单独的锁对象,类似于:private final Object lock = new Object();在你的计算器中,为读者提供一个吸气剂. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |