Java OCA OCP Practice Question 2508

Question

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();
       }
   }
}
  • a The threads main and p1 will always deadlock.
  • b The threads main and p1 might not deadlock.
  • c Compilation error
  • d Runtime exception


b

Note

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().




PreviousNext

Related