ran*_*psp 6 java multithreading
我相信主线程不能在子线程之前死掉.但有什么方法可以检查吗?我在下面写了一个简单的程序.任何人都可以证明它几乎将理论抛在一边吗?
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());
}
}
Run Code Online (Sandbox Code Playgroud)
根据詹姆斯的建议.我尝试了以下程序.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
代码正在执行时,执行完整线程转储并查看所有线程处于活动状态.
class AnotherClass {
public static void main(String arrp[]) throws Exception {
Thread t = new Thread() {
public void run() {
while (true) {
// do nothing
}
}
};
t.start();
//Sleep for 15 seconds
Thread.sleep(15000);
}
}
Run Code Online (Sandbox Code Playgroud)
编译并执行它:
$ javac AnotherClass.java
$ java AnotherClass
Run Code Online (Sandbox Code Playgroud)
找到过程:
$ ps -ef | grep AnotherClass
nikunj <<10720>> 10681 2 12:01:02 pts/9 0:04 java AnotherClass
nikunj 10722 10693 0 12:01:05 pts/6 0:00 grep Another
Run Code Online (Sandbox Code Playgroud)
采取线程转储:
$ kill -3 <<10720>>
Run Code Online (Sandbox Code Playgroud)
输出(摘录):
"main" prio=10 tid=0x00039330 nid=0x1 waiting on condition [0xffbfe000..0xffbfe2a8]
at java.lang.Thread.sleep(Native Method)
at AnotherClass.main(AnotherClass.java:12)
"Thread-0" prio=10 tid=0x00a1b770 nid=0x12 runnable [0xadc7f000..0xadc7f970]
at AnotherClass$1.run(AnotherClass.java:7)
Run Code Online (Sandbox Code Playgroud)
进行另一个线程转储(15秒后):
$ kill -3 <<10720>>
Run Code Online (Sandbox Code Playgroud)
新产出(摘录):
"Thread-0" prio=10 tid=0x00a1b770 nid=0x12 runnable [0xadc7f000..0xadc7f970]
at AnotherClass$1.run(AnotherClass.java:7)
Run Code Online (Sandbox Code Playgroud)
结论: 主要消失了.
来自http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html:
Java虚拟机继续执行线程,直到发生以下任一情况:
已调用类Runtime的exit方法,并且安全管理器已允许执行退出操作.
所有非守护程序线程的线程都已死亡,无论是通过从run方法调用返回还是抛出传播超出run方法的异常.
在您的情况下,当主线程死亡时,JVM不会退出,因为您仍然在运行已创建的线程,并且默认情况下它们是守护进程,因为:
当且仅当创建它的线程当前标记为守护程序线程时,新创建的线程最初被标记为守护程序线程.方法setDaemon可用于更改线程是否是守护程序.
引用:http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#setDaemon(boolean)