java多线程Future.cancel(true)取消线程,线程还是会执行catch与finally里面的代码,只要资源回收的代码没有乱写,不必担心资源回收问题

1.代码展示

public static void main(String[] args) {
        //定义线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 30, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        //信号量定义
        CountDownLatch countDownLatch = new CountDownLatch(2);
        //提交异步任务1
        Future<Integer> future1 = threadPoolExecutor.submit(() -> {
            try {
                System.out.println("任务1获取连接");
                Thread.sleep(1000);
                System.out.println("任务1开始处理查询结果");
                return 1 ;
            } catch (Exception e){
                System.out.println("任务1catch="+e.getMessage());
                return null ;
            }finally {
                //信号量递减
                countDownLatch.countDown();
                System.out.println("任务1归还连接");
            }
        });
        //提交异步任务2
        Future<Integer> future2 = threadPoolExecutor.submit(() -> {
            try {
                System.out.println("任务2获取连接");
                Thread.sleep(20000);
                System.out.println("任务2开始处理查询结果");
                return 2 ;
            } catch (Exception e){
                System.out.println("任务2catch="+e.getMessage());
                return null ;
            }finally {
                //信号量递减
                countDownLatch.countDown();
                System.out.println("任务2归还连接");
            }
        });

        //等待都执行完成
        try {
            countDownLatch.await(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("*****************************开始打印执行结果*********************************");

        if(future1.isDone()){
            Integer integer = null;
            try {
                integer = future1.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("任务1执行结果="+integer);
        }else {
            System.out.println("任务1执行结果=null");
            future1.cancel(true);
        }

        if(future2.isDone()){
            Integer integer = null;
            try {
                integer = future2.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("任务2执行结果="+integer);
        }else {
            System.out.println("任务2执行结果=null");
            future2.cancel(true);
        }
    }

2.执行结果

任务1获取连接
任务2获取连接
任务1开始处理查询结果
任务1归还连接
*****************************开始打印执行结果*********************************
任务1执行结果=1
任务2执行结果=null
任务2catch=sleep interrupted
任务2归还连接

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值