java-多线程,一个线程执行完毕,其他线程跳出运算-利用线程组ThreadGroup(子线程中执行当前线程组的interrupt方法)

todo:有空测试一下线程池的shutdown方法看能否成功

Runable

package sample;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class testRunnable1 implements Runnable {

    boolean mark = false;


    @Override
    public void run() {

        SimpleDateFormat sdf = new SimpleDateFormat("yymmdd");
        int count = 0;

        System.out.println("Thread start:" + sdf.format(new Date()));
        for (int i = 0; i < 1000; i++) {

            if (mark) {
                Thread.currentThread().getThreadGroup().interrupt();

                for (int is = 0; is < 10; i++) {
                    Thread.currentThread().getThreadGroup().interrupt();
                }
                break;
            }
            count++;
            try {

                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + ":" + count + "");
            } catch (InterruptedException e) {
                e.printStackTrace();

                System.out.println(Thread.currentThread().getThreadGroup().getName() + ":" + Thread.currentThread().getName() + "被终止");
            }
        }
        System.out.println("Thread end  :" + sdf.format(new Date()));

    }

}

调用

package sample;

import java.io.IOException;

class propertyT{


    static volatile  boolean flag = true;


    public static void main(String[] args) throws InterruptedException, IOException {

//        Utils.write("r3","22");
//        Utils.write("r5","55");

        ThreadGroup tg1 = new ThreadGroup("我是一个新的线程组1");
        ThreadGroup tg2 = new ThreadGroup("我是一个新的线程组2");



        testRunnable1 tr1 = new testRunnable1();
        new Thread(tg1,tr1,"tr1").start();

        testRunnable1 tr2 = new testRunnable1();
        new Thread(tg1,tr2,"tr2").start();



        testRunnable1 tr = new testRunnable1();
        new Thread(tg2,tr,"tr").start();

        testRunnable1 tr3 = new testRunnable1();
        new Thread(tg2,tr3,"tr3").start();

        testRunnable1 tr4 = new testRunnable1();
        new Thread(tg2,tr4,"tr4").start();


        Thread.sleep(5000);
        //给tg2线程组停止所有线程
        tr.mark = true;

    }

}

重点代码

Thread.currentThread().getThreadGroup().interrupt()
需要多调用几次

for (int is = 0; is < 10; i++) {
    Thread.currentThread().getThreadGroup().interrupt();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值