Hello,
How can i keep child threads running after parent thread dies?
I tried to use setDaemon method but it didn't work.
Any idea?
Printable View
Hello,
How can i keep child threads running after parent thread dies?
I tried to use setDaemon method but it didn't work.
Any idea?
in a command line application, such as when we launch from the static void main(String[] args), when the main thread exits, that effectively causes the VM to start doing its shutdown..
Daemon threads are really only good in applets (i think), to allow the thread to run when the [applet] is otherwise finished running, beacuse typically the lifespan of the Java vm in a web browser plugin, is the duration the browser is open, not the duration the user is browsing the page containing the applet.
so for the command line applications, to cause it to wait until a child thread finishes, we need a piece of busy waiting logic in the main thread
Code:public static void main(String[] args) {
// your thread, of your implementation of runnable
Thread childThread = new Thread(new Runnable() {
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println("in child thread");
try { Thread.sleep(1000); } catch (InterruptedException ex) {}
}
}
});
System.out.println("main thread is starting child thread.");
childThread.start();
System.out.println("main thread is done, now just waiting for child thread to finish.");
while (childThread.isAlive()) {
// sleep for some small amount of time to prevent consuming cpu cycles in a tight while loop
try { Thread.sleep(20); } catch (InterruptedException ex) {}
}
System.out.println("child thread has exited. now main thread exiting too");
} // main
I Think, This is you Question , "Parent Thread waits until child finish its work".
Join() helps you!...
Just Use
try
{
childThread.join(); // Parent waits until the ChildThread dead
}
catch(InterruptedException ie) //should catch Interrupted Exception
{
System.out.println(ie.getMessage());
}
//main Ends...