通过线程组实现批量停止线程

代码demo:

import java.util.concurrent.TimeUnit;

public class StopMuchThread {

    static class MyThread extends Thread {
        private ThreadGroup group;
        private String name;


        public MyThread(ThreadGroup group, String name) {
            super(group, name);
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "开始运行");
            while (!this.isInterrupted()) {
                //无限循环
            }
            System.out.println(Thread.currentThread().getName() + "结束运行");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadGroup threadGroup = new ThreadGroup("测试线程组");
        for (int i = 0; i < 5; i++) {
            MyThread thread = new MyThread(threadGroup, "线程" + i);
            thread.start();
        }
        TimeUnit.SECONDS.sleep(5);
        threadGroup.interrupt();
        System.out.println("线程组调用了interrupt()方法");
    }
}

运行结果:
在这里插入图片描述

总结

可以发现,只要是归属于同一个线程组下的线程,一旦线程组调用了interrupt()方法,就可以将该组下的所有运行时线程批量停止。

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/107760888