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.
添加回答
举报