Java OCA OCP Practice Question 2990

Question

Given:

2. public class Main extends Thread {  
3.   static int count = 0;  
4.   public void run() {  
5.     for(int i = 0; i < 100; i++) {  
6.       if(i == 5 && count < 3) {  
7.         Thread t = new Main(names[count++]);     
8.         t.start();  /* ww  w  .java 2 s  .  c om*/
9.         // insert code here  
10.       }  
11.       System.out.print(Thread.currentThread().getName() + " ");  
12.     }  
13.   }  
14.   public static void main(String[] args) {  
15.     new Main("t0").start();  
16.   }    
17.   Main(String s) { super(s); }  
18.   String[] names = {"t1", "t2", "t3"};  
19. } 

And these two fragments:

  • I. try { t.join(); } catch(Exception e) { }
  • II. try { Thread.currentThread().join(); } catch(Exception e) { }

When each fragment is inserted independently at line 9, which are true? (Choose all that apply.)

  • A. With fragment I, t0 completes last.
  • B. With fragment I, t3 completes last.
  • C. With fragment II, t0 completes last.
  • D. With fragment II, t3 completes last.
  • E. With both fragments, compilation fails.
  • F. With fragment I, the code never completes.
  • G. With fragment II, the code never completes.


A and G are correct.

Note

With fragment I, t0 joins to t1, which joins to t2, which joins to t3.

Next, t3 completes and returns to t2, which completes and returns to t1, which completes and returns to t0.

With fragment II, t0 starts t1 and then joins to itself.

Then, t1 starts t2 and joins to itself.

Then, t2 starts t3 and joins to itself.

Finally, t3 runs and when it completes, t2 hangs, waiting for itself to finish.




PreviousNext

Related