Java synchronization
Consider the following cases of synchronization, and think of what should be the result in each case: 1. Object "obj" has two methods - M1() and M2(). None of them is synchronized. Two threads T1 and T2, want to run M1() and M2() respectively. Both threads share a common obj object. What will be the result? Result: Each thread will be able to execute its desired method. 2. Object "obj" has two methods - M1() and M2(). Only M2 is synchronized. Two threads T1 and T2, want to run M1() and M2() respectively. Both threads share a common obj object. What will be the result? Result: Each thread will be able to execute its desired method. Since T1 does not need a lock on obj to execute M1(). 3. Object "obj" has two methods - M1() and M2(). Both are synchronized. Two threads T1 and T2, want to run M1() and M2() respectively. Both threads share a common obj object. What will be the result? Result: Since to execute each method a lock is needed on the object, the first thread to get a lock on obj will be able to execute its desired method. 4. Object "obj" has one synchronized - M() . Two threads T1 and T2, want to run M(). Both threads have share a common obj object. What will be the result? Result: The thread that first gets the lock is able to execute the method first. And if this thread does not leave the object lock, then the other thread keeps on waiting. Since each thread needs a lock on obj. Download source code here. Exercise : What will happen if the methods above are static?
2 Comments:
When you enhance or modify a number of methods of the superclass then you should use extends. Here you are providing implementation for only one method.
So, here you should use...
class Thread implements Runnable.
This is a good implementation practice, as you will not be loading both the classes at runtime.
Static makes no difference in the results.
Post a Comment
<< Home