Java OCA OCP Practice Question 2747

Question

Given:

public class Main implements Runnable {
   static Thread t1;
   static MyClass h, h2;

   public void run() {
      if (Thread.currentThread().getId() == t1.getId())
         h.adjust();//ww w.  jav a  2s.  c o  m
      else
         h2.view();
   }

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

class MyClass {
   static int x = 5;

   synchronized void adjust() {
      System.out.print(x-- + " ");
      try {
         Thread.sleep(200);
      } catch (Exception e) {
         ;
      }
      view();
   }

   synchronized void view() {
      try {
         Thread.sleep(200);
      } catch (Exception e) {
         ;
      }
      if (x > 0)
         adjust();
   }
}

Which are true? (Choose all that apply.)

  • A. Compilation fails.
  • B. The program could deadlock.
  • C. The output could be: 5 4 3 2 1
  • D. The program could produce thousands of characters of output.
  • E. If the sleep() invocations were removed the chances of deadlock would decrease.
  • F. If the view() method was not synchronized the chances of deadlock would decrease.


C is correct.

Note

It might look like this code could deadlock, but it can't.

The two Main threads are both using the same synchronized methods, but they aren't trying to use each other's instances.




PreviousNext

Related