Given the following class:
class MyClass { // w w w . j a v a 2 s .c o m synchronized void notStaticMethod() { for (long n=0; n<100000000000L; n++) System.out.println(n); } synchronized static void staticMethod() { for (long n=0; n<100000000000L; n++) System.out.println(n); } }
Suppose thread A and thread B both have references to each of two instances of MyClass.
These references are named myClass1 and myClass2.
Which statements are true?
Choose all correct options.
staticMethod()
, then thread B may not execute myClass1.staticMethod()
. staticMethod()
, then thread B may not execute myClass2.staticMethod()
. notStaticMethod()
, then thread B may not execute myClass1.staticMethod()
. notStaticMethod()
, then thread B may not execute myClass1.notStaticMethod()
. notStaticMethod()
, then thread B may not execute myClass2.notStaticMethod()
. A, B, D.
There are three locks to consider:
A and B are true because staticMethod()
is controlled by the class lock.
C is false because myClass1.notStaticMethod()
is controlled by myClass1's object lock, while myClass1.staticMethod()
is controlled by the class lock.
D is true because both threads are trying to execute code controlled by myClass1's object lock.
E is false because thread A is executing code controlled by myClass1's object lock, while thread B wants to execute code controlled by myClass2's object lock.