Java OCA OCP Practice Question 3018

Question

Given:

class Shape {
   static int x = 5;

   synchronized void adjust(Shape y) {
      System.out.print(x-- + " ");
      y.view(y);/* w  w  w .ja  v  a 2s .c o m*/
   }

   synchronized void view(Shape z) {
      if (x > 0)
         z.adjust(z);
   }
}

public class Main implements Runnable {
   static Thread t1;
   static Shape g, g2;

   public void run() {
      if (Thread.currentThread().getId() == t1.getId())
         g.adjust(g2);
      else
         g2.view(g);
   }

   public static void main(String[] args) {
      g = new Shape();
      g2 = new Shape();
      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 could be 5 4 3 2 1
  • C. The output could be 5 4 3 2 1 0
  • D. The program could produce thousands of lines of output.
  • E. The program could deadlock before producing any output.
  • F. The output could be "5 ", followed by the program deadlocking.


B, C, and F are correct.

Note

This program could deadlock with "g" waiting to invoke view() while "g2" waits to invoke adjust().

If the code doesn't deadlock, then B and C are correct, B being the more common output.

A and D are incorrect based on the above.

E is incorrect because the code can't deadlock until the y.view(y) invocation is attempted.




PreviousNext

Related