Is it still necessary to wait until each thread ends before closing the first?

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.

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章