我相信主线程不能先于子线程死掉。但是有什么办法可以检查吗?我在下面写了一个简单的程序。抛开理论,谁能证明这一点?
class childre extends Thread
{
public void run()
{
for( int i=0 ; i<10 ;i++)
{
System.out.println( " child " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class ChildThreadb4main
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("main");
childre c1 = new childre();
c1.start();
for(int i=0;i<5;i++)
{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println( " child thread alive ? " + c1.isAlive());
}
}
根据 James 的建议。我尝试了以下程序。
public class MainChildDie {
public static void main(String ar[]){
final Thread mainThread = Thread.currentThread();
System.out.println("main run ");
new Thread(){
public void run(){
Thread childThread= Thread.currentThread();
for(int i=0; i<10;i++){
System.out.println( "child"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main alive " + mainThread.isAlive());
}
}.start();
}
}
最佳答案
来自 http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html :
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.
在您的情况下,当主线程终止时,JVM 不会退出,因为您仍然有创建的线程在运行,并且默认情况下它们是守护进程,因此:
The newly created thread is initially marked as being a daemon thread if and only if the thread creating it is currently marked as a daemon thread. The method setDaemon may be used to change whether or not a thread is a daemon.
引用:http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#setDaemon(boolean)
关于java - 主线程可以在子线程之前死掉吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8784333/