In the below code:
class Worker extends Thread {
Thread t;
public Worker(Thread thread) {
t=thread;
}
public void run() {
try {
t.join();
} catch(InterruptedException e) {
System.out.println("Exception is thrown and caught");
}
System.out.println(Thread.activeCount());
System.out.print("|work|");
}
public static void main(String[] args) {
Thread t=Thread.currentThread();
Worker worker = new Worker(t);
worker.setDaemon(true);
worker.start();
System.out.println("Exit from main method");
}
}
Since worker is a daemon thread joined on main() thread, |work| should never be printed since the user thread main() completes first, and since worker is a daemon thread it too is stopped when the main() thread dies. But, the output I get is as follows : Exit from main method 1 |work|
Please clarify this query for me.
After many many executions of the program, I have observed the following different outputs:
without Thread.sleep(1000) :
Exit from main method 2
Exit from main method 1 |work|
Exit from main method 2 |work|
with Thread.sleep(1000) :
Exit from main method 2 |work|
Exit from main method
Notice the first output without sleep() method. |work| is not printed but the thread count is shown to be 2. Does this mean main() thread execution ended after Thread.activeCount() but before |work| is printed? In third output seems like main() ended after execution of both these statements.
Now, I was never expecting Thread.activeCount() to be 2, since the daemon thread worker is joined on user thread main(), which means when Thread.activeCount() is executed, there will only be worker thread and no main() thread.
InterruptedExceptionhappen? - user207421catchblock for that exception. - user207421