Java OCA OCP Practice Question 2941

Question

Given:

public class Main {
   public static void main(String[] args) throws Exception {
      Thread t1 = new Thread(new Main1());
      Thread t2 = new Thread(new Main1());
      t1.start();//from w w  w.  jav a 2  s .  co m
      t2.start();
      t1.join(500);
      new Main1().run();
   }
}

class Main1 implements Runnable {
   public void run() {
      for (int i = 0; i < 5; i++) {
         try {
            Thread.sleep(200);
         } catch (Exception e) {
            System.out.print("e ");
         }
         System.out.print(Thread.currentThread().getId() + "-" + i + " ");
      }
   }
}

What is the result?

  • A. Compilation fails.
  • B. The main thread will run mostly before t1 runs.
  • C. The main thread will run after t1, but together with t2.
  • D. The main thread will run after t2, but together with t1.
  • E. The main thread will run after both t1 and t2 are mostly done.
  • F. The main thread's execution will overlap with t1 and t2's execution.


F   is correct.

Note

The key to this question is join(500).

This means that the main thread will try to join to the end of t1, but it will only wait 500 milliseconds for t1 to complete.

If t1 doesn't complete (and it will take at least 1000 milliseconds for t1 to complete), the main thread will start after waiting 500 milliseconds.




PreviousNext

Related