• 关于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);
    
        }
    
    

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

  • 相关阅读:
    二维数组实现01背包
    一维数组实现01背包
    js实现最长子串算法
    mysql__存储过程
    mysql 分页查询 limit
    转:严重: Exception loading sessions from persistent storage
    struts2---ValueStack对象
    struts2----ognl
    什么是JavaBean?
    EL表达式
  • 原文地址:https://www.cnblogs.com/lameclimber/p/13690279.html
Copyright © 2020-2023  润新知