I wrote a Multithreaded program in Java given below :-
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Counter counter = new Counter();
int val = counter.getValue();
while(val < 5){
val = counter.getValue();
System.out.println("In main thread : "+val);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Counter implements Runnable {
private int countValue;
Counter(){
countValue = 0;
Thread thread = new Thread(this ,"Counter A");
Thread thread1 = new Thread(this ,"Counter B");
thread.start();
thread1.start();
}
int getValue(){
return countValue;
}
@Override
public void run() {
// TODO Auto-generated method stub
while( countValue < 5){
System.out.println("In child thread : "+ ++countValue );
try {
Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and output of program is output :-
In main thread : 0
In child thread : 2
In child thread : 1
In child thread : 3
In child thread : 3
In child thread : 4
In child thread : 5
In main thread : 5
Can anybody explain me in detail how this output came.Thank you in advance