23

will main thread exit before child threads complete execution?

i read in 2 articles

http://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-management.html

in the above article, In "Thread Termination" para, it states in Red " if the parent thread terminates, all of its child threads terminate as well."

http://www.roseindia.net/java/thread/overview-of-thread.shtml

in the above article, the last line in that page states "The main() method execution can finish, but the program will keep running until the all threads have complete its execution.".

i fee they are contradictory. if i am wrong, Please experts correct me.

In my program, a program with Main method calls the constructor of 2 threads . in the constructor of the respective threads, i am having the start() method .

     TestA  A = new TestA("TestA");
     TestB  B = new TestB("TestB");

     public TestA(String name) {
    System.out.println(name);
    t = new Thread(this);
    t.start();
}

i would like to know what happens, main thread terminates before child threads complete execution? if so, will the child threads anyway, continue their execution??

i tried running the program, some times all the child threads are getting executed complete even if the main thread exits. In the 2 threads , i am processing some files. in testA thread A alone, 1 file alone is not getting processed some times. but many times, all the files are getting processed and i do not have any issues.

user1257836
  • 309
  • 2
  • 5
  • 10
  • The answers below are good but they haven't explained why `if the parent thread terminates, all of its child threads terminate as well.` is written in the linked article. Actually in C/C++ unlike Java, when the main thread terminates, the process terminates and all other threads stop. – dark_prince Jan 17 '22 at 13:30

3 Answers3

37

Java makes a distinction between a user thread and another type of thread known as a daemon thread. The difference between these two types of threads is that if the JVM determines that the only threads running in an application are daemon threads (i.e., there are no user threads), the Java runtime closes down the application. On the other hand, if at least one user thread is alive, the Java runtime won't terminate your application.

When your main() method initially receives control from the Java runtime, it executes in the context of a user thread. As long as the main-method thread or any other user thread remains alive, your application will continue to execute.

In your case, the threads are user threads and hence are allowed to complete before the main thread exits.

i am processing some files. in testA thread A alone, 1 file alone is not getting processed some times. but many times

The reason for the above is could be something else than thread exits. It could be file locks, synchronization issue etc.

Thread (Java SE 10 & JDK 10):

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
Suresh Kumar
  • 11,241
  • 9
  • 44
  • 54
  • Thanks for the detailed explanation. you have mentioned that "In your case, the threads are user threads and hence are allowed to complete before the main thread exits." Here you mean "main thread" to be Java run time not the program with main method() . correct? – user1257836 Mar 11 '12 at 06:08
  • 1
    the class which has main method and the threads which get created inside main method are all User threads . all these threads are independent get executed concurrently. Because i gave System.out.println("exit of main method"); at the end of main method. this gets printed before the system.out.println() in the child threads. this made me think that the main thread (class which has main method) can exit even before the child threads. is this fine and correct way of behaviour? – user1257836 Mar 11 '12 at 06:14
  • can you please clarify what do you mean by file locks? thanks in advance!! – user1257836 Mar 11 '12 at 19:01
  • 1
    "Here you mean "main thread" to be Java run time not the program with main method() . correct?". Yes. "this gets printed before the system.out.println() in the child threads. this made me think that the main thread (class which has main method) can exit even before the child threads. is this fine and correct way of behaviour?" Though the main thread completes, the JVM doesn't shut down until there are still non daemon threads executing in the application. – Suresh Kumar Mar 12 '12 at 03:39
  • 1
    "can you please clarify what do you mean by file locks?" When a process/thread is accessing a file, it obtains a lock on the file and when another process/thread tries to access the same file, it will result in an error. – Suresh Kumar Mar 12 '12 at 03:39
  • Suresh, I apologize for editing your post, please revert back my changes if possible. – Pavel Molchanov Jun 27 '18 at 01:53
4

The background threads will keep running, even if the MAIN thread completes.

If you want MAIN to stop them (example, when MAIN is complete), have your MAIN set a "keep running" flag variable (which you must set as "volatile"), which the threads occasionally look at. MAIN sets it to false (variable) or null (object) when MAIN wants to stop them. When it's false or null, then the thread must "return;".

This is somewhat complex to implement, there are many ways, but easiest is to make your Runnable an inner class, so that your Runnable has easy sharing of the flag.

For the best implementations, look up this technique in Java applets' start/stop routines.

Griwes
  • 8,805
  • 2
  • 43
  • 70
John
  • 49
  • 1
  • First in practical, its not wise to control via flag, especially in a main method. You can achieve it by using daemon thread instead – kidnan1991 Oct 07 '19 at 01:35
2

Once the main thread exits, it takes the children with it. Perhaps by "finish" the second article simply means no more operation other than waiting for the children. Once the main thread calls System.exit(0); it's over -- every body dies.

Say you have two threads running: threadA and threadB. in the main method. The first code is the nice way of terminating the thread -- just one of many ways:

 threadA.start();
 threadB.start();
 final long intercept = 300;
 long startTime = System.currentTimeMillis();
 while (threadA.isAlive() && mis.isAlive()) {
    threadA.join(intercept);
if (System.currentTimeMillis() - startTime > intercept) {
   threadB.interrupt();
   threadA.interrupt();
   threadA.join();
}
}
System.exit(0);

Below is an abrupt way of killing all threads from within main:

System.exit(0);
kasavbere
  • 5,873
  • 14
  • 49
  • 72
  • Thanks for the response. I never used System.exit(0) in my program."Once the main thread exits, it takes the children with it".am still not clear. the program which has main method creates 2 threads and its get completed. but the child threads that were spawned will continue , is that not correct? – user1257836 Mar 11 '12 at 06:44