I started t1 thread in my main method and want to stop main thread but my t1 thread still running.
It is possible? how?
public static void main(String[] args)
{
Thread t1=new Thread()
{
public void run()
{
while(true)
{
try
{
Thread.sleep(2000);
System.out.println("thread 1");
}
catch(Exception e)
{}
}
}
};
t1.start();
}
Best Answer
When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons:
• It is the thread from which other "child" threads will be spawned.
• It must be the last thread to finish execution. When the main thread stops, your program terminates.
One more thing, program terminates when all non-daemon threads die (daemon thread is a thread marked with setDaemon(true)).
Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in setDaemon.