Java OCA OCP Practice Question 3212

Question

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

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

A .   class PingPong extends Thread {
             public void run() {
                     System.out.println("ping ");
             }/*  w  w w  . j  av a2  s . c  om*/
             public static void main(String []args)  {
                     Thread pingPong = new PingPong();
                     System.out.print("pong");
             }
      }

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

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

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


D.

Note

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

After that it prints "pong".

So, this implementation correctly prints "ping pong".

Why are the other options wrong?.

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

So, this program only prints "pong".

The program always prints "ping pong", but it is misleading.

This program directly calls the run() method instead of calling the start() method.

So, this is a single threaded program.

The main thread and the worker thread execute independently without any coordination.

So, depending on which thread is scheduled first, you can get "ping pong" or "pong ping" printed.




PreviousNext

Related