zoukankan      html  css  js  c++  java
  • 杀死future处理的阻塞线程

    public class Test{
        public static void main(String[] args){
            ExecutorService pool = Executors.newFixedThreadPool(4);
            BlockingQueue<Future> queue = new LinkedBlockingQueue<Future>();
            for (int i = 0; i < 4; i++) {
                Future<Integer> future = pool.submit(new A());
                queue.add(future);
            }
            int j = 0;
            for (int i = 0; i < 4; i++) {
                Future<Integer> future = null;
                try {
                    future = queue.take();
                    j += future.get(2,TimeUnit.SECONDS);
    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    System.out.println("超时了");
                    future.cancel(true);   // 取消这个线程执行的任务,让线程空闲,线程池的这个线程可以执行新的任务
                }
            }
            System.out.println("超时线程总和"+(4-j));
            /*
                超时了
                超时了
                总和2
            */
        }
        
        static class A implements Callable<Integer>{
            @Override
            public Integer call() throws InterruptedException {
    
                Thread.sleep(5000);
                return 1;
            }
        }
    }
    
    
  • 相关阅读:
    CF1260F
    牛客挑战赛34 A~E
    CSP-S2019游记&拆塔记
    6424. 【NOIP2019模拟2019.11.13】我的订书机之恋
    CF1257E/F
    6423. 【NOIP2019模拟11.11】画
    1222/2516. Kup
    Comet OJ
    浅析CSS定位
    css文字颜色渐变的3种实现
  • 原文地址:https://www.cnblogs.com/72808ljup/p/5359232.html
Copyright © 2011-2022 走看看