Java OCA OCP Practice Question 3056

Question

Given:

2. public class Main extends Thread {  
3.   public static void main(String[] args) {  
4.     System.out.print(Thread.currentThread().getId() + " ");  
5.     Thread t1 = new Thread(new Main());   
6.     Thread t2 = new Thread(new Main());  
7.     t1.start();  /* ww  w.jav  a 2  s  .  com*/
8.     t2.run();  
9.   }  
10.   public void run() {  
11.     for(int i = 0; i < 2; i++)     
12.       System.out.print(Thread.currentThread().getId() + " ");   
13.   }
14.} 

Which are true? (Choose all that apply.)

  • A. No output is produced.
  • B. The output could be 1 1 9 9 1
  • C. The output could be 1 2 9 9 2
  • D. The output could be 1 9 9 9 9
  • E. An exception is thrown at runtime.
  • F. Compilation fails due to an error on line 4.
  • G. Compilation fails due to an error on line 8.


B is correct.

Note

It's legal to get the ID of the "main" thread.

It's also legal to call run() directly, but it won't start a new thread.

In this case, it's just invoking run() on main's call stack.

In this code, t2 is never started, so there are only two threads (main and t1), therefore only two IDs are in the output.

D is incorrect because no thread's getId() method is called more than three times.




PreviousNext

Related