Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always necessary to wait for every thread to terminate before actually closing main one?

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?

like image 358
Phate Avatar asked Jul 23 '14 12:07

Phate


1 Answers

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.

like image 101
Seelenvirtuose Avatar answered Sep 22 '22 12:09

Seelenvirtuose