【发布时间】:2018-02-07 13:21:24
【问题描述】:
我对 Java 多线程还很陌生,我找到了一些 responses 来做我想做的事情。然而,作为 java 线程的新手,我仍然很难跟踪响应。
基本上这就是我所拥有的:
private final ExecutorService mFixedThreadPool;
public ThreadPool(int threadCount) {
mFixedThreadPool = Executors.newFixedThreadPool(threadCount);
}
public interface Task {
void phase1();
void phase2();
void phase3();
}
public void executeBatch(List<Runnable> tasks) {
tasks.forEach(task -> mFixedThreadPool.execute(task::phase1));
tasks.forEach(task -> mFixedThreadPool.execute(task::phase2));
tasks.forEach(task -> mFixedThreadPool.execute(task::phase3));
//only return on the main thread once all the tasks are complete.
//(Dont destroy threadpool as the "executeBatch" method will be called in a loop)
}
我想暂停或停止或等待调用“executeBatch”的线程,直到这批工作完成。我知道可以使用 mFixedThreadPool.shutdown() 执行此操作,然后等待其成功关闭,但是我想经常多次重用线程,因此每次关闭都是低效的。
【问题讨论】:
-
我不明白。您已经链接到一个答案,该答案从字面上告诉您您需要做什么。这里有什么问题?
-
@Michael 我刚刚更新了代码,但基本上我已经阅读了我链接到的回复以及我可以找到的针对这个特定问题的其他一些回复,但我并没有真正明白Futures 集合的要点或我将如何实施该答案。就像“myRunnable”任务一样,我是否需要为每个任务都这样做,future.get() 是什么?应该做的,等等。
标签: java multithreading parallel-processing