What is the output of the following code?
class MyClass{}//ww w . ja v a 2 s . c o m class Main implements Runnable { public void run() { synchronized(MyClass.class) { System.out.println("Hand made paper"); } } public static void main(String args[]) throws Exception { Thread p1 = new Thread(new Main()); p1.start(); synchronized(MyClass.class) { p1.join(); } } }
b
You can't determine the exact time that a scheduler starts the execution of a thread.
So the thread p1 can acquire the lock on a monitor associated with class MyClass,
execute the p1's method run()
, and exit before method main()
gets its turn to acquire a lock on MyClass.class and call p1.join()
.