java线程,java父线程子线程

问:在父线程中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:
Tags:  java线程同步 java线程池 java多线程 java线程

延伸阅读

最新评论

发表评论