Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is that possible fro a thread ???

 
abhay jain
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is that possible for an other thread to be alive after main() Thread dies ???
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It doesn't even have to die in a dramatic way (for example because of an uncaught exception caused by a division by zero, as Campbell demonstrates). Other threads will remain running after the main thread ends, unless they are daemon threads. You can make a thread a daemon thread by calling setDaemon(true) on it.

Note the API documentation:
java.lang.Thread wrote:
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.

  •  
    Rob Spoor
    Sheriff
    Pie
    Posts: 20608
    63
    Chrome Eclipse IDE Java Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    A JVM doesn't end until all non-daemon* threads have stopped. That means that if you launch another non-daemon thread, and that thread remains alive when the main thread ends, the JVM does not end yet. The Event Dispatcher Thread (EDT) of AWT/Swing is often such a thread. Threads created for java.util.Timer objects are also such threads. And of course, any thread without setDaemon(false) called on them are such threads.

    * All daemon threads will end when all non-daemon threads have ended as well. Check out Thread's setDaemon method for more info.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic