Java OCA OCP Practice Question 3076

Question

Given:

class Shape implements Runnable {
   public void run() {
      for (int i = 0; i < 8; i++) {
         try {// w w  w. ja v  a 2  s. c  o  m
            Thread.sleep(200);
         } catch (Exception e) {
            System.out.print("exc ");
         }
         System.out.print(i + " ");
      }
   }
}

public class Main {
   public static void main(String[] args) throws Exception {
      Shape j1 = new Shape();
      Thread t1 = new Thread(j1);
      t1.start();
      t1.sleep(500);
      System.out.print("pre ");
      t1.interrupt();
      t1.sleep(500);
      System.out.print("post ");
   }
}

Assuming that sleep() sleeps for about the amount of time specified in its argument, and that all other code runs almost instantly, which output is likely? (Choose all that apply.)

  • A. exc
  • B. 0 1 pre exc post
  • C. exc 0 1 2 3 4 5 6 7
  • D. pre post 0 1 2 3 4 5 6 7
  • E. pre exc 0 1 post 2 3 4 5 6 7
  • F. 0 1 pre exc 2 3 4 post 5 6 7


F	 is correct.

Note

Remember that sleep() is static and that when a sleeping thread is interrupted, an InterruptedException is thrown.

In this code, the t1 thread is started, and then the main thread sleeps for 500 milliseconds.

While the main thread is sleeping, t1 sleeps and then iterates a couple of times.

When main wakes up, it interrupts t1 (which is almost certainly sleeping), causing the exception, which is handled.

Then, main goes back to sleep for a while, t1 iterates a few more times, and main reawakens and completes, and finally t1 completes.




PreviousNext

Related