我相信主线程不能死在子线程之前。但是有什么方法可以检查吗?我在下面写了一个简单的程序。任何人都可以证明它实际上离开理论吗?可以在主线程死前子线程
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());
}
}
从詹姆斯的建议后。我尝试了下面的程序。
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();
}
}
“主”线程没有什么特别之处。它只是你看到的第一个(有其他的守护进程线程)如果你制作了所有的“后台”线程,守护进程线程,主进程退出时程序将退出。否则,程序将继续运行。 – 2012-01-09 08:09:34