我相信主線程不能死在子線程之前。但是有什麼方法可以檢查嗎?我在下面寫了一個簡單的程序。任何人都可以證明它實際上離開理論嗎?可以在主線程死前子線程
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