我粘贴了下面的代码。这是足够的评论。清除等待()。当它来到这里时,它会跳到另一个街区。那部分我很橡木。我的疑问是为什么我们使用 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.
}
}
}