Is it always necessary to wait for the completion of each thread before the actual closure of the main one?

Suppose I have a main thread and a normal thread, the execution of which is greater than the first.

Something like that:

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 leave such a code? Or would it be more proper to execute join () on a thread to ensure that it completed correctly?

+4
source share
5 answers

This is one of the questions for which the answer is: It depends.

, , . , , . , , , , .

: JVM , . JVM , daemon.

+7

.

join System.exit.

. , .

+1

JVM -daemon .

setDaemon (true) , JVM , Thread . join() , , , , .

+1

, , , , " , " / ", , " .

, java, , . , , , .

3 , .

1: //.

2: .

3: .

, , , , , .. Thread 2, Thread 3, Thread 1. , , . .

+1

If a thread does not work in an infinite loop, it will end soon, the question is whether you want to wait for the completion of this thread or not? You can wait if further processing depends on the result of starting the stream. If this thread just does some work and ends, just leave it.

0
source

All Articles