Suppose I have a main thread and a normal thread, whose execution lasts more than the former one.
Something like it:
public class Test{
private int count;
public void doTest(){
(new MyThread()).start();
}
public static void main(String[] args){
Test t = new Test();
t.doTest();
}
private class MyThread extends Thread{
public void run(){
while(count < 100){
count++;
..wait some secs ...
}
}
}
}
Is it wrong to just leave code like that? Or would it be more correct perform a join() on the thread so to make sure that it correctly ends?
This is one of the question, for which the answer is: It depends.
There is no technical reason to have the main thread running till all other threads are terminated. In fact, you can handle the main thread like every other thread. As I recommend to not have a thread keeping alive when it already has done its business and can be terminated, a main thread that only starts other threads should simply terminate after starting the others.
Remind: The JVM itself is not terminated when the main thread terminates. The JVM will only terminate when all non-daemon threads are terminated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With