Java OCA OCP Practice Question 2689

Question

Given:

class Main extends Thread {
   private static Thread t;

   public void run() {
      if (Thread.currentThread() == t) {
         System.out.print("1 ");
         synchronized (t) {
            doSleep(2000);//  w ww.j  a v a2s. c o  m
         }
         System.out.print("2 ");
      } else {
         System.out.print("3 ");
         synchronized (t) {
            doSleep(1000);
         }
         System.out.print("4 ");
      }
   }

   private void doSleep(long delay) {
      try {
         Thread.sleep(delay);
      } catch (InterruptedException ie) {
         ;
      }
   }

   public static void main(String args[]) {
      t = new Main();
      t.start();
      new Main().start();
   }
}

Assuming that sleep() sleeps for about the amount of time specified in its argument, and that all other code runs almost instantly, which are true? (Choose all that apply.).

  • A. Compilation fails.
  • B. An exception could be thrown.
  • C. The code could cause a deadlock.
  • D. The output could be 1 3 4 2
  • E. The output could be 1 3 2 4
  • F. The output could be 3 1 4 2
  • G. The output could be 3 1 2 4


D, E, F, and G are correct.

Note

When one thread prints "1", the other thread prints "3" and then either thread could hold the monitor lock of "t".

The other thread will wait until the lock is released and both threads will continue to normal completion.




PreviousNext

Related