問:在父線程中New了一個子線程,想在停止父線程時也停止子線程,應該怎么做?
答:
從某種程度上講,做不到。
不管是父線程還是子線程,這只不過是在運行時誰建了誰時用的,一旦所謂的字線程被啟動,這兩個線程是沒有先后貴賤區分的。
任何線程是沒有辦法把另外一個線程終止的。
如果你一定想你說的那樣是線的話,下面是唯一個可行方案。在"父線程"建立“子線程”時,把“父線程”的instance傳過去,在“子線程”里,不停的check"父線程"是否還存活,如果否,停止。
相反的,如果"父線程"需要在"子線程"終了時結束,在"父線程"建立“子線程”時,留住“子線程”的instance然后keep checking whether it's still alive.
================================================================================
只有在所有非守護進程都停止的情況下,jvm才退出。main線程停止jvm也不一定退出:
1: public class TestMitiThread {
2:
3: public static void main(String[] rags) {
4:
5: System.out.println(Thread.currentThread().getName() + " 線程運行開始!");
6:
7: new MitiSay("A").start();
8:
9: new MitiSay("B").start();
10:
11: System.out.println(Thread.currentThread().getName() + " 線程運行結束!");
12:
13: }
14:
15:
16:
17: class MitiSay extends Thread {
18:
19: public MitiSay(String threadName) {
20:
21: super(threadName);
22:
23: }
24:
25: public void run() {
26:
27: System.out.println(getName() + " 線程運行開始!");
28:
29: for (int i = 0; i < 10; i++) {
30:
31: System.out.println(i + " " + getName());
32:
33: try {
34:
35: sleep((int) Math.random() * 10);
36:
37: } catch (InterruptedException e) {
38:
39: e.printStackTrace();
40:
41: }
42:
43: }
44:
45: System.out.println(getName() + " 線程運行結束!");
46:
47: }
48:
49:
50:
運行結果:
main 線程運行開始!
main 線程運行結束!
A 線程運行開始!
0 A
1 A
B 線程運行開始!
2 A
0 B
3 A
4 A
1 B
5 A
6 A
7 A
8 A
9 A
A 線程運行結束!
2 B
3 B
4 B
5 B
6 B
7 B
8 B
9 B
B 線程運行結束!