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.)
F is correct.
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.