interrupt 一个 thread group 会导致该 group 中所有 active 线程全部 interrupt,也就是说该 group 中每一个线程的中断标识都被设置了。
public final void interrupt() {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
checkAccess();
for (int i = 0 ; i < nthreads ; i++) {
threads[i].interrupt();
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
groupsSnapshot[i].interrupt();
}
}
分析源码,可以看到在 interrupt 内部会执行所有 thread 的 interrupt 方法,并且会递归获取子 group,然后执行它们各自 interrupt 方法。
package concurrent;
import java.util.concurrent.TimeUnit;
public class ThreadGroupInterrupt {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("TestGroup");
new Thread(group, () -> {
while (true) {
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
break;
}
}
System.out.println("t1 will exit");
}, "t1").start();
new Thread(group, () -> {
while (true) {
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
break;
}
}
System.out.println("t2 will exit");
}, "t2").start();
try {
TimeUnit.MILLISECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
group.interrupt();
}
}
t1 will exit
t2 will exit
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/123744113
内容来源于网络,如有侵权,请联系作者删除!