Java OCA OCP Practice Question 2809

Question

Given:

4. public class Main extends Thread {  
5.   public static void main(String[] args) throws Exception {  
6.     Thread t1 = new Thread(new Main());  
7.     t1.start();  /*  ww w  .ja  va2s .c  o  m*/
8.     // insert code here  
9.     for(int i = 0; i < 1000; i++)  // Loop #1  
10.       System.out.print(Thread.currentThread().getName() + " ");  
11.   }  
12.   public void run() {  
13.     for(int i = 0; i < 1000; i++)  // Loop #2  
14.       System.out.print(Thread.currentThread().getName() + " ");  
15. } } 

Which code, inserted independently at line 8, will make most (or all) of Loop #2's iterations run before most (or all) of Loop #1's iterations? (Choose all that apply.).

  • A. // just a comment
  • B. t1.join();
  • C. t1.yield();
  • D. t1.sleep(1000);


B and D are correct.

Note

The join() method will tack the main thread's execution to the end of t1's execution.

The t1.sleep(1000) method will put the main thread to sleep for one second (remember sleep() is static!!!).

A is incorrect because the two threads' run order will be unpredictable.

C is incorrect because yield() might cause a tiny interruption (where 1000 milliseconds would be a HUGE interruption), but it probably wouldn't significantly change the run order.




PreviousNext

Related