Java OCA OCP Practice Question 2273

Question

Here is a class named Main that extends the Thread class.

Which of the following Main class implementations correctly prints "main" from the worker thread and then prints "pong" from the main thread?.


A.

class Main extends Thread {
    public void run() {
        System.out.println("main ");
    }//from  w ww.  j  a  va  2  s  . c om
    public static void main(String []args)  {
        Thread mainPong = new Main();
        System.out.print("pong");
    }
}

B.

class Main extends Thread {
     public void run() {
         System.out.println("main ");
     }
     public static void main(String []args)  {
         Thread mainPong = new Main();
         mainPong.run();
         System.out.print("pong");
     }
}

C.

class Main extends Thread {
    public void run() {
        System.out.println("main");
   }
    public static void main(String []args)  {
        Thread mainPong = new Main();
        mainPong.start();
        System.out.println("pong");
    }
}

D.

class Main extends Thread {
    public void run() {
        System.out.println("main");
    }
             public static void main(String []args) throws InterruptedException{
                 Thread mainPong = new Main();
                 mainPong.start();
                 mainPong.join();
                 System.out.println("pong");
             }
         }


D.

Note

the main thread creates the worker thread and waits for it to complete (which prints "main").

after that it prints "pong".

So, this implementation correctly prints "main pong".

option a) the main() method creates the worker thread, but doesn't start it.

So, the code given in this option only prints "pong".

option b) the program always prints "main pong", but it is misleading.

the code in this option directly calls the run() method instead of calling the start() method.

So, this is a single threaded program: both "main" and "pong" are printed from the main thread.

option c) the main thread and the worker thread execute independently without any coordination.

(note that it does not have a call to join() in the main method.) So, depending on which thread is scheduled first, you can get "main pong" or "pong main" printed.




PreviousNext

Related