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);
    
        }
    
    

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

  • 相关阅读:
    基于flask的web微信
    Scrapy框架
    python爬虫之Selenium
    python爬虫之request and BeautifulSoup
    CMDB的四种模式
    Django之CURD插件2
    Django之CURD插件
    在代码中使用Autolayout – intrinsicContentSize和Content Hugging Priority
    iOS事件传递&响应者链条
    CAEmitterLayer 粒子发射Layer的相关属性
  • 原文地址:https://www.cnblogs.com/lameclimber/p/13690279.html
Copyright © 2011-2022 走看看