Frnds,
I have a small confusion on
Thread synchronization. When you have synchronized method, basically it acquires the lock for the object and releases it when it is done. Today I ran a sample
test program for threads. I have a class named
Test with two methods(one synchronized and one non-synchronized method). In my program I am creating two threads and in the run method I am calling those two methods of
Test class. For better understanding here I copied my program
When i run the above program I get this output:
Synchronized method T2
Synchronized method T2
Synchronized method T2
Synchronized method T2
Synchronized method T1When Thread T2 has acquired the lock for Test object and working on how Thread T1 can acquire the lock??
Synchronized method T2
Synchronized method T1
Synchronized method T2
Synchronized method T2
Synchronized method T2
Synchronized method T2
Synchronized method T2
@@@@@@Non-Synchronized method T2
Synchronized method T1
@@@@@@Non-Synchronized method T2
Synchronized method T1
@@@@@@Non-Synchronized method T2
Synchronized method T1
@@@@@@Non-Synchronized method T2
Synchronized method T1
@@@@@@Non-Synchronized method T2
Synchronized method T1
@@@@@@Non-Synchronized method T2
Synchronized method T1
@@@@@@Non-Synchronized method T2
@@@@@@Non-Synchronized method T2
@@@@@@Non-Synchronized method T2
@@@@@@Non-Synchronized method T2
Synchronized method T1
Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
@@@@@@Non-Synchronized method T1
So, in the above output while one thread is processing synchronized method of Test object the other thread has got the lock for the same method? Why is that? If I have two synchronized methods then the other thread waits to get the lock till one thread is finished. Guyz shouldnt I use non-synchronized method in an object with synchronized method?
Thanks,
Ravi
[ January 29, 2008: Message edited by: Ravi Kotha ]
[ January 29, 2008: Message edited by: Ravi Kotha ]