/**
* 當(dāng)網(wǎng)絡(luò)和代碼耗時高, 線程池再多, 一樣很快耗盡線程池;
* 網(wǎng)絡(luò)和代碼耗時穩(wěn)定, 適度增加線程池?cái)?shù)量可提高單位時間內(nèi)任務(wù)處理量;
*/
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線程循環(huán)任務(wù)隊(duì)列
// CallerRunsPolicy卡住了, 循環(huán)任務(wù)隊(duì)列也會被卡主, 都是在main線程執(zhí)行
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線程中循環(huán)任務(wù)隊(duì)列
把任務(wù)提交給子線程或任務(wù)隊(duì)列,如果隊(duì)列滿了, 或者沒有子線程接收任務(wù),
則走拒絕策略, CallerRunsPolicy 在main線程執(zhí)行子任務(wù), 因?yàn)闀ㄗain線程循環(huán)任務(wù)隊(duì)列。
ThreadPoolExecutor
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true)) // 子線程中執(zhí)行任務(wù)
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command); // main線程中執(zhí)行任務(wù)
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
*/
線程池
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。