/**
* 当网络和代码耗时高, 线程池再多, 一样很快耗尽线程池;
* 网络和代码耗时稳定, 适度增加线程池数量可提高单位时间内任务处理量;
*/
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);
}
*/
线程池
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...