i have a simple code piece bellow:
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();
b.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);
}
}
class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();
}
}
}
Result:
Waiting for b to complete...
Total is: 4950
and i have a problem why we need use this code, i am not clearly here.
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();
}
when i dont use synchronized here, i have the same result.