jdk1.8 ThreadPoolExecutor线程池内线程超时如何优雅取消

3 篇文章 0 订阅

线程池 某一个线程任务超时,如何真正取消正在执行的线程呢? 

直接上代码吧

方案1:

static class WarpFeature<T> {
    Future<T> f;
    String name;

    public WarpFeature(Future<T> f, String name) {
        this.f = f;
        this.name = name;
    }
}

@Test
public void s1_1_cancle() {

    Logger log = LoggerFactory.getLogger(TestThread.class);

    ExecutorService executorService = new ThreadPoolExecutor(1, 1, 1L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1), r -> new Thread(r, "测试线程")
            , new ThreadPoolExecutor.DiscardPolicy());

    List<WarpFeature<Object>> futures = new ArrayList<>();
    futures.add(new WarpFeature<>(executorService.submit(() -> {
        boolean flag = true;//只是模拟条件用
        Thread threadNow = Thread.currentThread();
        long time = System.currentTimeMillis();
        int i = 0;
        while (flag) {
            if (System.currentTimeMillis() - time == 1100) {
                i++;
                log.info("任务1执行中,模拟耗时步骤[{}]",i);
                if (threadNow.isInterrupted()) {
                    log.error("任务1被中断");
                    throw new RuntimeException("任务1超时");
                }
                time = System.currentTimeMillis();
            }
        }
        log.info("任务1结束...模拟条件用");
        return null;
    }), "任务1"));

    for (WarpFeature<Object> future : futures) {

        try {
            future.f.get(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("InterruptedException{}", e.getMessage(), e);
        } catch (ExecutionException e) {
            log.error("ExecutionException{}", e.getMessage(), e);
        } catch (TimeoutException e) {
            future.f.cancel(true);
            log.info("{}超时了", future.name);

        }

    }
    log.info("下班啦");

    try {
        TimeUnit.SECONDS.sleep(300l);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值