Java OCA OCP Practice Question 2183

Question

What will be the result of attempting to compile and run the following program?

class R1 implements Runnable {
  public void run() {
    System.out.print(Thread.currentThread().getName());
  }/*  w  w w. jav a 2  s.c om*/
}
public class R2 implements Runnable {
  public void run() {
    new Thread(new R1(),"|R1a|").run();
    new Thread(new R1(),"|R1b|").start();
    System.out.print(Thread.currentThread().getName());
  }

  public static void main(String[] args) {
    new Thread(new R2(),"|R2|").start();
  }
}

    

Select the one correct answer.

  • (a) The program will fail to compile.
  • (b) The program will compile without errors and will print |R1a| twice and |R2| once, in some order, every time the program is run.
  • (c) The program will compile without errors and will print|R1b| twice and |R2| once, in some order, every time the program is run.
  • (d) The program will compile without errors and will print |R1b| once and |R2| twice, in some order, every time the program is run.
  • (e) The program will compile without errors and will print |R1a| once, |R1b| once, and |R2| once, in some order, every time the program is run.


(d)

Note

Calling the run() method on a Thread object does not start a thread.

However, the run() method of the Thread class will invoke the run() method of the Runnable object that is passed as argument in the constructor call.

In other words, the run() method of the R1 class is executed in the R2 thread, i.e., the thread that called the run() method of the Thread class.




PreviousNext

Related