亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

“主”線程的 Java 執行器

“主”線程的 Java 執行器

月關寶盒 2023-05-17 17:49:17
我想Executor從程序的&ldquo;主&rdquo;線程(類似于 Android 中的主循環程序)創建一個,然后運行直到它處理完提交給它的所有內容:public class MyApp {? private static Callable<Integer> task = () -> {? ? // ... return an int somehow ...? };? public static void main(String[] args) throws ExecutionException, InterruptedException {? ? ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));? ? Thread main = Thread.currentThread();? ? ExecutorService executorService = Executors.newSingleThreadExecutor(r -> main);? ? service.submit(task).addListener(() -> {? ? ? /// ... do something with the result ...? ? }, executorService);? ? executorService.awaitTermination(100, TimeUnit.SECONDS);? }}但我得到一個IllegalThreadState例外:SEVERE: RuntimeException while executing runnable MyApp$$Lambda$20/0x00000008000a6440@71f06a3c with executor java.util.concurrent.Executors$FinalizableDelegatedExecutorService@47add263java.lang.IllegalThreadStateException? ? at java.base/java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:926)? ? at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1343)? ? at java.base/java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:687)? ? at com.google.common.util.concurrent.AbstractFuture.executeListener(AbstractFuture.java:1137)? ? at com.google.common.util.concurrent.AbstractFuture.complete(AbstractFuture.java:957)? ? at com.google.common.util.concurrent.AbstractFuture.set(AbstractFuture.java:726)? ??我可以在一個新線程上開始一個ExecutorService線程,然后等待它,但這似乎很浪費。有沒有一種從當前線程創建一個Executor并等待它處理已提交給它的所有內容的好方法?
查看完整描述

4 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

使用 Guava 的MoreExecutors.newDirectExecutorService()

這將確保提交的代碼將在 ThreadPool 的同一線程中執行。我知道,這不是主線程,但至少您不會像您想要的那樣只為偵聽器創建其他新線程。

import com.google.common.util.concurrent.*;

import org.junit.jupiter.api.Test;

import java.util.concurrent.*;


class ExecutorTest {

? private static Callable<Integer> task = () -> {

? ? System.out.println("in call: " + Thread.currentThread().getName());

? ? TimeUnit.SECONDS.sleep(1);

? ? return 0;

? };

? @Test

? void test() throws InterruptedException {

? ? ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));

? ? ExecutorService executor = MoreExecutors.newDirectExecutorService();

? ? service.submit(task).addListener(() -> {

? ? ? System.out.println("in listener: " + Thread.currentThread().getName());

? ? }, executor);

? ? executor.awaitTermination(2, TimeUnit.SECONDS);

? }

}


查看完整回答
反對 回復 2023-05-17
?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

您正在嘗試在主線程中執行回調。直接的方法是調用get()

YourResult?result?=?service.submit(task).get();
/*?Do?something?with?your?result...?*/

如果您想異步執行回調,您可能會對CompletionStage

CompletableFuture.runAsync(task).thenAccept(r?->?/*?do?something?with?result?*/);



查看完整回答
反對 回復 2023-05-17
?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

此處invokeAll()記錄的方法?等待所有任務完成?您可以這樣做

executorService.invokeAll();


查看完整回答
反對 回復 2023-05-17
?
縹緲止盈

TA貢獻2041條經驗 獲得超4個贊

您可能正在尋找類似的東西CompletionService:您向其提交任務,它會按完成順序返回給您。

ExecutorService service = Executors.newFixedThreadPool(1);

ExecutorCompletionService<Integer> comp = new ExecutorCompletionService<>(service);


comp.submit(task);

// ... I assume you want to submit N tasks.


for (int i = 0; i < N; ++i) {

? Future<Integer> future = comp.take();

? Integer result = future.get();


? // ... do something with the result ...

}

這將在項目完成后立即對其進行處理。如果你能等到你擁有一切,然后一次性處理它,你可以使用番石榴Futures.allAsList


ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));

List<Callable<Integer>> tasks = ...;


List<ListenableFuture<Integer>> futures = new ArrayList<>();

for (Callable<Integer> task : tasks) {

? futures.add(service.submit(task));

}


ListenableFuture<List<Integer>> resultsFuture = Futures.allAsList(futures);

List<Integer> results = resultsFuture.get();


// Process the results.


查看完整回答
反對 回復 2023-05-17
  • 4 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號