ThreadGroup 的 interrupt 实战

x33g5p2x  于2022-03-28 转载在 其他  
字(1.2k)|赞(0)|评价(0)|浏览(153)

一 点睛

interrupt 一个 thread group 会导致该 group 中所有 active 线程全部 interrupt,也就是说该 group 中每一个线程的中断标识都被设置了。

二 ThreadGroup 的 interrupt 的源码

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

相关文章