Java OCA OCP Practice Question 2302

Question

What will the following program print when compiled and run?

public class Main {
  final static int[] intArray = new int[2];

  private static void pause() {
    while(intArray[0] == 0) {
      try { intArray.wait(); }
      catch (InterruptedException ie) {
        System.out.println(Thread.currentThread() + " interrupted.");
      }//from ww  w.j a va 2 s. c om
    }
  }

  public static void main (String[] args) {

    Thread runner = new Thread() {
      public void run() {
        synchronized (intArray) {
          pause();
          System.out.println(intArray[0] + intArray[1]);
    }}};

    runner.start();
    intArray[0] = intArray[1] = 10;
    synchronized(intArray) {
      intArray.notify();
    }
  }
}

Select the one correct answer.

  • (a) The program will not compile.
  • (b) The program will compile, but throw an exception when run.
  • (c) The program will compile and continue running once started, but will not print anything.
  • (d) The program will compile and print 0 and terminate normally, when run.
  • (e) The program will compile and print 20 and terminate normally, when run.
  • (f) The program will compile and print some other number than 0 or 20, and terminate normally, when run.


(e)

Note

The runner thread can only proceed if intArray[0] is not 0.

If this element is not 0, it has been initialized to 10 by the main thread.

If this element is 0, the runner thread is put into the wait set of the intArray object, and must wait for a notification.

The main thread only notifies after initializing both elements of the array to 10.

Calling the notify() method on an object with no threads in its wait set does not pose any problems.

A thread can only call notify() on an object whose lock it holds.

Therefore, the last synchronized block in the main() method is necessary.




PreviousNext

Related