I have a Thread Object - ThreadB which add numbers 1 - 100. I create 2 instances of it - b & c.
Start the 2 threads(different instances) and run it.
Result:
Waiting for b to complete...
Total is: 4950
Waiting for c to complete...
Why does my second instance does not complete...
Java code:
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();
ThreadB c = new ThreadB();
b.start();
c.start();
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
synchronized(c){
try{
System.out.println("Waiting for c to complete...");
c.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + c.total);
}
}
}
class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();
}
}
}