4 回答

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);
? }
}

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?*/);

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.
添加回答
舉報