Java OCA OCP Practice Question 2298

Question

What will the following program print when compiled and run?

public class Tank {
  private boolean isEmpty = true;

  public synchronized void emptying() {
    pause(true);//from www  .  j a  va2  s  . c o m
    isEmpty = !isEmpty;
    System.out.println("emptying");
    notify();
  }

  public synchronized void filling() {
    pause(false);
    isEmpty = !isEmpty;
    System.out.println("filling");
    notify();
  }

  private void pause(boolean flag) {
    while(flag ? isEmpty : !isEmpty) {
      try {
        wait();
      } catch (InterruptedException ie) {
        System.out.println(Thread.currentThread() + " interrupted.");
      }
    }
  }

  public static void main(String[] args) {
    final Tank token = new Tank();
    (new Thread("A") { public void run() {for(;;) token.emptying();}}).start();
    (new Thread("B") { public void run() {for(;;) token.filling();}}).start();
  }
}

Select the one correct answer.

  • (a) The program will compile and continue running once started, but will not print anything.
  • (b) The program will compile and continue running once started, printing only the string "emptying".
  • (c) The program will compile and continue running once started, printing only the string "filling".
  • (d) The program will compile and continue running once started, always printing the string "filling" followed by the string "emptying".
  • (e) The program will compile and continue running once started, printing the strings "filling" and "emptying" in some order.


(d)

Note

Since the two methods are mutually exclusive, only one operation at a time can take place on the tank that is a shared resource between the two threads.

The method emptying() waits to empty the tank if it is already empty.

When the tank becomes full, it empties the tank and sets the condition that the tank is empty.

The method filling() waits to fill the tank if it is already full.

When the tank becomes empty, it fills the tank and sets the condition that the tank is full.

Since the tank is empty to start with, it will be filled first.

Once started, the program will continue to print the string "filling" followed by the string "emptying".

Note that the while loop in the pause() method must always check against the field isEmpty.




PreviousNext

Related