Java OCA OCP Practice Question 2784

Question

Given:

public class Main implements Runnable {
   static Thread t1;
   static int x = 5;

   public void run() {
      if (Thread.currentThread().getId() == t1.getId())
         shove();//from   w  w w  .jav  a 2  s. c o m
      else
         push();
   }

   static synchronized void push() {
      shove();
   }

   static void shove() {
      synchronized (Main.class) {
         System.out.print(x-- + " ");
         try {
            Thread.sleep(2000);
         } catch (Exception e) {
            ;
         }
         if (x > 0)
            push();
      }
   }

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

Which are true? (Choose all that apply.)

  • A. Compilation fails.
  • B. The output is 5 4 3 2 1
  • C. The output is 5 4 3 2 1 0
  • D. The program could deadlock.
  • E. The output could be 5, followed by deadlock.
  • F. If the sleep() invocation was removed, the chance of deadlock would decrease.
  • G. As it stands, the program can't deadlock, but if shove() was changed to synchronized, then the program could deadlock.


C is correct.

Note

It might look like this code could deadlock, but there is only one lock, so no deadlock can occur.




PreviousNext

Related