/**
* 当网络和代码耗时高, 线程池再多, 一样很快耗尽线程池;
* 网络和代码耗时稳定, 适度增加线程池数量可提高单位时间内任务处理量;
*/
private static ExecutorService executorTask = new ThreadPoolExecutor(
1,
1,
100L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(2),
new ThreadPoolExecutor.CallerRunsPolicy());
public static void main(String[] args) throws InterruptedException {
Callable<String> callable = () -> {
Thread.sleep(2000L);
String tname = Thread.currentThread().getName();
System.out.println(tname);
return tname;
};
ArrayList<Callable<String>> callables = new ArrayList<>();
for (int i = 0; i < 10; i++) {
callables.add(callable);
}
executorTask.invokeAll(callables);
executorTask.shutdown();
}
/*
AbstractExecutorService
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
if (tasks == null)
throw new NullPointerException();
ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
boolean done = false;
try {
//在main线程循环任务队列
// CallerRunsPolicy卡住了, 循环任务队列也会被卡主, 都是在main线程执行
for (Callable<T> t : tasks) {
RunnableFuture<T> f = newTaskFor(t);
futures.add(f);
execute(f);
}
for (int i = 0, size = futures.size(); i < size; i++) {
Future<T> f = futures.get(i);
if (!f.isDone()) {
try {
f.get();
} catch (CancellationException ignore) {
} catch (ExecutionException ignore) {
}
}
}
done = true;
return futures;
} finally {
if (!done)
for (int i = 0, size = futures.size(); i < size; i++)
futures.get(i).cancel(true);
}
}
main线程中循环任务队列
把任务提交给子线程或任务队列,如果队列满了, 或者没有子线程接收任务,
则走拒绝策略, CallerRunsPolicy 在main线程执行子任务, 因为会卡住main线程循环任务队列。
ThreadPoolExecutor
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true)) // 子线程中执行任务
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command); // main线程中执行任务
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
*/
线程池
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。