一直对主线程、子线程、守护线程的概念与之间的关系不太理解,比如是不是主线程运行退出后其创建的子线程是否也会退出,主线程创建子线程后,子线程与主线程是否还有依赖关系?是否需要设置为守护线程后才接触依赖?今天特地用java做了个实验。
实验使用代码如下:
import java.lang.Thread;
class Thread1 extends Thread{
public void run() {
for (int i=0; i<2; i++) {
System.out.println("\nThread1 say:Hello,World " + i);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("\nThread1 is over");
}
}
class Thread2 extends Thread {
public void run() {
System.out.println("\nThread2 create a child thread Thread1");
new Thread1().start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\nThread2 is over");
}
}
public class TestThread extends Thread{
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\nTestThread create a child thread Thread2");
new Thread2().start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\nTestThread is over");
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Thread t = new TestThread();
//t.setDaemon(true);
t.start();
System.out.println("\nmain create a child thread TestThread");
int count = 0;
while(Thread.activeCount()>1) {
System.out.print(Thread.activeCount() + " ");
count++;
if (count%10 == 0) {
System.out.println();
}
Thread.currentThread().sleep(200);
}
System.out.println(Thread.activeCount());
System.out.println("\nmain is over");
}
}
运行后结果如下:
main create a child thread TestThread
2 2 2 2 2
TestThread create a child thread Thread2
Thread2 create a child thread Thread1
Thread1 say:Hello,World 0
4 4 4 4 4
TestThread is over
3 3 3 3 3 3 3 3 3 3
Thread2 is over
2 2 2 2 2 2 2 2 2 2
Thread1 say:Hello,World 1
2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2
2 2 2 2 2
Thread1 is over
1
main is over
从运行结果看,一开始main创建了一个ThreadTest后总线程数为2,后ThreadTest建了一个线程Thread2,Thread2建了一个线程Thread1,此时线程总数为4,后TestThead运行结束,线程总数为3,Thread2运行结束,线程为2,最后Thread1结束后线程数为1,main结束后线程数为0。所以线程的结果是不依赖与其父线程的。父与子之间没有依赖关系。但是只要线程存在,java虚拟机是不会退出的。除非将线程设置为守护线程。
setDaemon
public final void setDaemon(boolean on)
-
将该线程标记为守护线程或用户线程。当正在运行的线程都是守护线程时,Java 虚拟机退出。
该方法必须在启动线程前调用。