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

[4476 byte] By [AnanSmritia] at [2007-11-27 0:07:46]
# 1
Thread scheduling is unpredictable, after all.Output is normal as follows;Incrementing 1 Thread-0Decrementing 0 Thread-0Incrementing 1 Thread-2Incrementing 2 Thread-1Decrementing 1 Thread-2Decrementing 0 Thread-1
hiwaa at 2007-7-11 16:06:22 > top of Java-index,Core,Core APIs...
# 2

You would only reliably get the output you expect if you had this:

public void run() {

synchronized (obj)

{

obj.increment();

obj.decrement();

}

}

ejpa at 2007-7-11 16:06:22 > top of Java-index,Core,Core APIs...
# 3
Hi,Thanks for your answer.
AnanSmritia at 2007-7-11 16:06:22 > top of Java-index,Core,Core APIs...