我创建了一个线程池来处理任务,处理完任务后,我发现我无法添加并启动其他任务?如何修复它?如果我将执行器更改为executor = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("timeOutThread"));
,它将正常运行.但是如果由于超时而取消任务,这是否会导致内存泄漏?
ExecutorService executor = new ThreadPoolExecutor(3,
3, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1),
new NamedThreadFactory(
"timeOutThread"));
List<Callable<String>> callableList = new ArrayList<>();
IntStream.range(0, 3).forEach(index -> {
callableList.add(() -> request(index));
});
List<Future<String>> futureList = executor.invokeAll(callableList, 1, TimeUnit.SECONDS);
for (int i = 0; i < futureList.size(); i++) {
Future<String> future = futureList.get(i);
try {
list.add(future.get());
} catch (CancellationException e) {
log.info("timeOut task:{}", i);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
Thread.sleep(1000);
callableList.clear();
IntStream.range(0, 3).forEach(index -> {
callableList.add(() -> request(index));
});
long start1 = System.currentTimeMillis();
// Task java.util.concurrent.FutureTask@5fdcaa40 rejected from java.util.concurrent.ThreadPoolExecutor@6dc17b83
List<Future<String>> futureList = executor.invokeAll(callableList, 1, TimeUnit.SECONDS);
for (int i = 0; i < futureList.size(); i++) {
Future<String> future = futureList.get(i);
try {
list.add(future.get());
} catch (CancellationException e) {
log.info("timeOut Task:{}", i);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public String request() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(200000);
return "A";
}