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

相关文章:

  • 2022-12-23
  • 2021-09-13
  • 2021-05-07
  • 2021-09-16
  • 2022-01-03
  • 2021-05-28
  • 2021-09-03
  • 2022-01-08
猜你喜欢
  • 2022-12-23
  • 2021-08-01
  • 2021-06-03
  • 2022-01-08
  • 2022-02-06
  • 2022-12-23
  • 2022-02-22
相关资源
相似解决方案