Case 1: m1() and m2() are not synchronized
t1 uses a1 and calls m1()
t2 uses a2 and calls m2()
both thread t1 and t2 can run at the same time because both threads are using different objects.
Case 2: m1() and m2() are synchronized
t1 uses a1 and calls m1()
t2 uses a2 and calls m2()
both thread t1 and t2 can run at the same time because both threads are using different objects.
by default synchronization will acquire lock on the object, since here both are using different object locking will not happen.
Case 3: m1() and m2() are synchronized
t1 uses a1 and calls m1()
t2 uses a1 and calls m2()
both thread t1 and t2 cannot run at the same time because both threads are using same object.
if t1 first access m1() then t2 will have to wait for t1 to complete running m1()
Case 4: m1() is static and m2() is non static and both are synchronized
t1 uses a1 and calls m1()
t2 uses a1 and calls m2()
both thread t1 and t2 can run at the same time because though both threads are using same object when t1 first access m1() it is not accessing via a1 object rather it will use A class for accessing the static method that is A.m1() is what called. For doing the same A.Class object will be created and it will be synchronized using A.Class object and t2 will be using a1 object for locking since both objects are different they can work parallel.
Case 5: m1() is static and m2() is static and both are synchronized
t1 uses a1 and calls m1()
t2 uses a1 and calls m2()
both thread t1 and t2 cannot run at the same time because though both threads are using same object (A.Class object)
No comments:
Post a Comment