Java OCA OCP Practice Question 3136

Question

Consider the following program:

class Worker extends Thread {
        public void run()  {
               System.out.println(Thread.currentThread().getName());
        }// w w  w .  j  a v  a 2 s.  c  om
}

public class Main {
        public static void main(String []args) throws InterruptedException {
               Thread.currentThread().setName("Main ");
               Thread worker = new Worker();
               worker.setName("Worker ");
               worker.start();
               Thread.currentThread().join();
               System.out.println(Thread.currentThread().getName());
        }
}

Which one of the following options correctly describes the behavior of this program?

  • a) When executed, the program prints the following: "Worker Main ".
  • b) When executed, the program prints "Worker ", and after that the program hangs (i.e., does not terminate).
  • c) When executed, the program prints "Worker " and then terminates.
  • d) When executed, the program throws IllegalMonitorStateException.
  • e) The program does not compile and fails with multiple compiler errors.


b)

Note

The statement Thread.currentThread() in the main() method refers to the "Main" thread. Calling the join() method on itself means that the thread waits itself to complete, which would never happen, so this program hangs (and does not terminate).




PreviousNext

Related