zoukankan      html  css  js  c++  java
  • 关于Future踩过的坑

    package com.swiftpass.spi.thread;
    
    import java.util.Random;
    import java.util.concurrent.Callable;
    
    public class TestThread implements Callable<Boolean> {
    
        public Boolean call() throws Exception {
            int i = new Random().nextInt(4);
            if(i%2==1){
                System.out.println(Thread.currentThread().getName()+"执行异常");
                throw new RuntimeException("111111");
            }
            System.out.println(Thread.currentThread().getName()+"执行成功");
            return true;
        }
    }
    
    
    @Test
        public void test() throws InterruptedException {
            ExecutorService executorService = Executors.newFixedThreadPool(100);
            List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
            for (int i = 1; i < 100; i++) {
                TestThread testThread = new TestThread();
                Future<Boolean> future = executorService.submit(testThread);
                futures.add(future);
            }
                for(Future<Boolean> future :futures){
                    try{
                        Boolean aBoolean = future.get();
                    }catch (Exception e){
                    }
                }
    
    
            System.out.println("回归主流程");
            Thread.sleep(1000000);
    
        }
    

    这样写会等所有线程结束后回归主流程

     @Test
        public void test1() throws InterruptedException {
            ExecutorService executorService = Executors.newFixedThreadPool(100);
            List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
            for (int i = 1; i < 100; i++) {
                TestThread testThread = new TestThread();
                Future<Boolean> future = executorService.submit(testThread);
                futures.add(future);
            }
            try {
                for (Future<Boolean> future : futures) {
    
                    Boolean aBoolean = future.get();
                }
            } catch (Exception e) {
            }
    
    
            System.out.println("回归主流程");
            Thread.sleep(1000000);
    
        }
    
    

    这样实现,只要一个抛出异常,就直接返回主流程了,然后子线程会继续跑,不会结束。

  • 相关阅读:
    【2021 ECUG Con】聚势而来,与你相约花开时
    为 Nginx 添加 HTTP 基本认证(HTTP Basic Authentication)
    centos6 yum 源失效 404
    [nsis]安装包反编译
    Web安全测试学习笔记-DVWA-盲注(使用sqlmap)
    Shellcodeloader免杀过火绒
    C#创建快捷方式-转载自ConExpress
    C#运行新线程,也可打开网页
    C#判断指定文件是否存在-转载mmgx(仅为方便找一下)
    C# 文件夹创建方法
  • 原文地址:https://www.cnblogs.com/lameclimber/p/13690279.html
Copyright © 2011-2022 走看看