Java OCA OCP Practice Question 2903

Question

Given:

4. public class Main implements Runnable {  
5.   static int id = 1;  
6.   public void run() {  
7.     try {  // ww  w.jav a 2 s. c  o  m
8.       id = 1 - id;  
9.       if(id == 0) { pick(); } else { release(); }  
10.     } catch(Exception e) { }  
11.   }  
12.   private static synchronized void pick() throws Exception {  
13.     System.out.print("P ");    System.out.print("Q ");  
14.   }  
15.   private synchronized void release() throws Exception {  
16.     System.out.print("R ");    System.out.print("S ");  
17.   }  
18.   public static void main(String[] args) {  
19.     Main st = new Main();  
20.     new Thread(st).start();  
21.     new Thread(st).start();    
22.  } } 

Which are true? (Choose all that apply.)

  • A. The output could be P Q R S
  • B. The output could be P R S Q
  • C. The output could be P R Q S
  • D. The output could be P Q P Q
  • E. The program could cause a deadlock.
  • F. Compilation fails.


A, B, and C are correct.

Note

Since pick() is static and release() is non- static, there are two locks.

If pick() was non- static, only A would be correct.

D is incorrect because line 6 swaps the value of id between 0 and 1.

There is no chance for the same method to be executed twice.

E and F are incorrect based on the above.




PreviousNext

Related