Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes When Main Thread Stops ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "When Main Thread Stops ?" Watch "When Main Thread Stops ?" New topic
Author

When Main Thread Stops ?

Srinivasa Vallabha
Greenhorn

Joined: Mar 08, 2001
Posts: 15
Hi all,
I got the following question and also the answer,
but I can't get the proper meaning out of this answer, can anybody please explain me, and if possible please give some coding example.
Q: I read this statement: "The main thread must be the last
thread to finish execution. When the main thread stops, the
program terminates." Is it true?
Answer: Absolutely wrong!
The correct one:
When you start a program, JVM creates one thread to run your
program. The JVM creates one user thread for running a program.
This thread is called main thread.
The main method of the class is called from the main thread.
If program spawns new threads from the main thread it does stop
until last thread id died.
Even if the main thread dies program keep running.
Thanks in advance
Srinivasa Vallabha
william kane
Ranch Hand

Joined: Nov 21, 2000
Posts: 260
public class TestMainThread{
public static void main(String args[]){
Thread tt=new ChildThread();
tt.start();
Thread.currentThread().stop();
System.out.println("Main stopped");

}
}
class ChildThread extends Thread{
public void run(){
try{
System.out.println("Sleep started");
Thread.sleep(50000);
System.out.println("Awakened");
}catch(Exception e){
e.printStackTrace();
}
}
}
The above is the example that reinstates the fact that the instance of the jvm exists until ALL THE NON DEAMON THREADS RETURN.
As u run the above example u can observe that even after the main thread (that started the child thread) is stopped the jvm continues to run.
clear???
ps donot use the stop method in development its depricated :-)
kane


Help me!Help you!!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When Main Thread Stops ?
 
Similar Threads
Thread
Thread
Thread Problem
Patrick Naughton and Threads
Is this JWhiz thread question wrong?