I am trying to write my first multi-threaded program in Java. I can't understand why we require this exception handling around the for loops. When I compile without the try/catch clauses it gives an InterruptedException
.
Here is the message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type InterruptedException
But when run with the try/catch, the sysout in the catch blocks are never displayed - implying no such exception was caught anyway!
public class SecondThread implements Runnable {
Thread t;
SecondThread() {
t = new Thread(this, "Thread 2");
t.start();
}
public void run() {
try {
for (int i=5; i>0; i--) {
System.out.println("thread 2: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("thread 2 interrupted");
}
}
}
public class MainThread {
public static void main(String[] args) {
new SecondThread();
try {
for (int i=5; i>0; i--) {
System.out.println("main thread: " + i);
Thread.sleep(2000);
}
}
catch (InterruptedException e) {
System.out.println("main thread interrupted");
}
}
}