gpt4 book ai didi

ThreadGroup 的 interrupt 实战

转载 作者:知者 更新时间:2024-03-13 03:26:03 27 4
gpt4 key购买 nike

一 点睛

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com