Java OCA OCP Practice Question 2506

Question

The thread p1 must start only after the thread p2 has completed its execution.

Which of the following code options, when inserted at //INSERT CODE HERE, will ensure this?.


1. class Main extends Thread {
2.     public void run() {
3.         System.out.println("executing");
4.     }//  w w w.  jav  a  2  s.c  o  m
5.     public static void main(String[] args) {
6.        Thread p1 = new Main();
7.        Thread p2 = new Main();
8.        p2.start();
9.        p1.start();
10.        //INSERT CODE HERE
11.    }
12. }
  • a p2.join();
  • b p1.join();
  • c p2.sleep(1000);
  • d p2.wait();
  • e p1.notify();
  • f None of the above


f

Note

Calling join from a thread ensures that the thread on which join is called completes before the calling thread completes its execution.

If the thread main calls p2.join() before starting the thread p1, it can ensure that p1 will start after p2 completes its execution.

For this to happen, main should call p2.join() at line 9 and p1.start() at line 10.

Options (a) and (b) are incorrect.

Calling p2.join() or p1.join() at line 10 will ensure that these threads complete their execution before the thread main completes its own execution.

Option (c) is incorrect.

The thread main executes p2.sleep().

Because sleep() is a static method, it will make main sleep for at least the specified time in milliseconds (if not interrupted).

Options (d) and (e) are incorrect because they won't serve the purpose.

Method wait() makes a thread release its object lock and makes it wait until another object that has acquired a lock on it calls notify() or notifyAll().

Also wait(), notify(), and notifyAll() must be called from a synchronized block of code or else JVM will throw an IllegalMonitorStateException.




PreviousNext

Related