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
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?
[ January 29, 2008: Message edited by: Ravi Kotha ] [ January 29, 2008: Message edited by: Ravi Kotha ]
You are correct that using the synchronized keyword does lock an object so another thread cannot enter its synchronized code until the thread that currently has the lock exits that block of code. However, one important fact is that the synchronized keyword synchronizes on the "this" keyword. So the following are essentially the same (there are slight differences in the sense that synchronization in the second method occurs once you get right inside the method):
In your example, each thread is initialized with a new instance of TestRSSI. So each one is actually synchronizing on a different instance of "this". You can try printing the hash code of the object and you'll see the two objects have different hash codes.
The following example does in fact synchronize:
Note that here both threads use the same instance of synchClass and thus synchronize on the same lock. Hope that helps.
Jeff [ January 29, 2008: Message edited by: Jeff Storey ]
posted 10 years ago
Now I got a better understanding of Thread. Thank you very much for your reply.