Invocation of Synchronized methods on the same object
Hi,
I have written 3 classes. In my first class ThreadExample15.java i have declared one instance variable counter. and two synchronized methods such as increment and decrement
In my second class ThreadExample16.java, I have a thread instance and called run method.
In my third class ThreadExample17.java, i have created 3 instances of class 2 and passing class 1 object as a parameter.
Please check the code and clarify my doubt
publicclass ThreadExample15{
privateint counter = 0;
publicsynchronizedvoid increment(){
counter = counter + 1;
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
System.out.println("ie " + ie.getMessage());
}
System.out.println("Incrementing " + counter +" " + Thread.currentThread().getName());
}
publicsynchronizedvoid decrement(){
counter = counter - 1;
System.out.println("Decrementing " + counter +" " + Thread.currentThread().getName());
}
publicvoid print(){
//System.out.println("Current value is " + counter + " " + Thread.currentThread().getName());
}
}
publicclass ThreadExample16implements Runnable{
private ThreadExample15 obj;
protected Thread myThread;
public ThreadExample16(ThreadExample15 ref){
obj = ref;
myThread =new Thread(this);
myThread.start();
}
publicvoid run(){
obj.increment();
obj.decrement();
}
}
publicclass ThreadExample17{
/**
* @param args
*/
publicstaticvoid main(String[] args){
// TODO Auto-generated method stub
ThreadExample15 obj =new ThreadExample15();
ThreadExample16 obj1 =new ThreadExample16(obj);
ThreadExample16 obj2 =new ThreadExample16(obj);
ThreadExample16 obj3 =new ThreadExample16(obj);
try{
obj1.myThread.join();
obj2.myThread.join();
obj3.myThread.join();
}catch(Exception ie){
System.err.println("ie");
}
}
}
My expected output is
Incrementing 1 Thread - 0
Decrementing 0 Thread - 0
.
.
........Thread - 2
but am getting weird result.
please can anyone help me understand this?
bye for now
sat

