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