Java OCA OCP Practice Question 65

Question

Which of the following are true about the following program?

public class Main {
   public static void main(String args[]) {
      MyThread t1 = new MyThread("t1");
      MyThread t2 = new MyThread("t2");
      t1.start();/*ww  w. j  a  v a  2  s.  co m*/
      t2.start();
   }
}

class MyThread extends Thread {
   public static Resource resource = new Resource();

   public void run() {
      for (int i = 0; i < 10; ++i) {
         resource.displayOutput(getName());
      }
   }

   public MyThread(String s) {
      super(s);
   }
}

class Resource {
   public Thread controller;
   boolean okToSend = false;

   public synchronized void displayOutput(String s) {
      try {
         while (!okToSend) {
            wait();
         }
         okToSend = false;
         System.out.println(s);
      } catch (InterruptedException ex) {
      }
   }

   public synchronized void allowOutput() {
      okToSend = true;
      notifyAll();
   }

   public Resource() {
      Thread controller = new Thread(new Controller(this));
      controller.start();
   }
}

class Controller implements Runnable {
   Resource resource;

   public Controller(Resource resource) {
      this.resource = resource;
   }

   public void run() {
      try {
         for (int i = 0; i < 100; ++i) {
            Thread.currentThread().sleep(2000);
            resource.allowOutput();
         }
      } catch (InterruptedException ex) {
      }
   }

}
  • A. The program always displays t1 10 times, followed by t2 10 times.
  • B. The program always displays t1 followed by t2.
  • C. The program displays no output.
  • D. The output sequence will vary from computer to computer.


D.

Note

The output is only synchronized one line at a time.




PreviousNext

Related