I found the following interesting question on a mock exam:
When application A below is run, two threads are created and started. Each
thread prints a message just before terminating. Which thread prints its message first?
class A {
private Thread t1, t2;
public static void main(
String[] args) {
new A();
}
A() {
t1 = new T1();
t2 = new T2();
t1.start();
t2.start();
}
class T1 extends Thread {
public void run() {
try {
sleep(5000); // 5 secs
}
catch (InterruptedException e) { }
System.out.println("t1 done");
}
}
class T2 extends Thread {
public void run() {
try {
t1.sleep(10000); // 10 secs
}
catch (InterruptedException e) { }
System.out.println("t2 done");
}
}
}
The answer is T1 since even though it looks like T2 will put T1 to sleep for an even longer amount of time, sleep() is a static method and executes on the currently running thread. Cool.
My question is, is why is ANYTHING printed out at all? I thought that an InterruptedException was only thrown when a sleeping or waiting thread received an interrupt() call from an executing thread. No such call is coded here. I didn't think that such an exception was automatically thrown when a sleeping or waiting thread entered the ready state. Am I wrong in so thinking?
Dan