join() is supposed to make main function wait until all the threads complete execution, but main is printing completed
before Thread-1
and Thread-2
completes execution.
I am unable to find error in the code. where's the mistake?
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo(String name) {
threadName = name;
}
public void run() {
System.out.println("Thread " + threadName + " exiting.");
}
public void start() {
if (t == null) {
t = new Thread (this, threadName);
t.start();
}
}
}
public class Problem2 {
public static void main(String[] args) {
ThreadDemo T1 = new ThreadDemo("Thread-1");
ThreadDemo T2 = new ThreadDemo("Thread-2");
T1.start();
T2.start();
try {
T1.join();
T2.join();
} catch (InterruptedException e) {
System.out.println("ERROR!");
}
System.out.println("completed");
}
}
Output
completed
Thread Thread-2 exiting.
Thread Thread-1 exiting.