守护线程与非守护线程

[TOC]

概念

进程中会同时存在二种线程:也就是守护线程和非守护线程,当所有的非守护线程结束时,程序也就终止了,同时会杀死进程中的所有守护线程。反过来说,只要任何非守护线程还在运行,程序就不会终止。

将线程转换为守护线程可以通过调用Thread对象的setDaemon(true)方法来实现。但是必须在thread.start()之前设置

Main线程结束,其他线程一样可以正常运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class ParentTest
{

public static void main(String[] args)
{
System.out.println("parent thread begin ");

ChildThread t1 = new ChildThread("thread1");
ChildThread t2 = new ChildThread("thread2");
t1.start();
t2.start();

System.out.println("parent thread over ");
}
}

class ChildThread extends Thread
{
private String name = null;

public ChildThread(String name)
{
this.name = name;
}

@Override
public void run()
{
System.out.println(this.name + "--child thead begin");

try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e);
}

System.out.println(this.name + "--child thead over");
}
}


--程序运行结果如下:
parent thread begin
parent thread over
thread2--child thead begin
thread1--child thead begin
thread2--child thead over
thread1--child thead over

Main线程结束,其他线程也可以立刻结束,当且仅当这些子线程都是守护线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class ParentTest
{

public static void main(String[] args)
{
System.out.println("parent thread begin ");

ChildThread t1 = new ChildThread("thread1");
ChildThread t2 = new ChildThread("thread2");
t1.setDaemon(true);
t2.setDaemon(true);

t1.start();
t2.start();

System.out.println("parent thread over ");
}
}
class ChildThread extends Thread
{
private String name = null;
public ChildThread(String name)
{
this.name = name;
}
@Override
public void run()
{
System.out.println(this.name + "--child thead begin");
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e);
}
System.out.println(this.name + "--child thead over");
}
}

执行结果如下:
parent thread begin
parent thread over
thread1--child thead begin
thread2--child thead begin