【发布时间】:2014-07-31 09:31:10
【问题描述】:
给定具有固定线程池的 Executor 服务,是否可以保证将任务确定性地分配给线程?更准确地说,假设只有两个线程,即 pool-thread-0 和 pool-thread-1,并且有 2 个要执行的任务的集合。我希望实现的是前一个线程总是执行第一个,而后者处理剩下的。
这是一个例子:
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = newFixedThreadPool(2,
new ThreadFactoryBuilder().setNameFormat("pool-thread-%d").build());
for (int i = 0; i < 5; i++) {
List<Callable<Integer>> callables = ImmutableList.of(createCallable(1), createCallable(2));
executorService.invokeAll(callables);
}
}
public static Callable<Integer> createCallable(final int task) {
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
currentThread().sleep(1000);
System.out.println(Thread.currentThread().getName() + " executes task num: " + task);
return task;
}
};
}
我机器的示例输出:
pool-thread-0 executes task num: 1
pool-thread-1 executes task num: 2
pool-thread-0 executes task num: 2
pool-thread-1 executes task num: 1
pool-thread-0 executes task num: 2
pool-thread-1 executes task num: 1
pool-thread-0 executes task num: 2
pool-thread-1 executes task num: 1
pool-thread-0 executes task num: 1
pool-thread-1 executes task num: 2
简而言之,我希望确保 pool-thread-0 始终执行第一个任务。任何帮助将不胜感激!
【问题讨论】:
-
我不这么认为。如果您需要这种确定性,为什么不设置两个队列和两个池?
-
即使可以,您为什么想要或关心?即使您可以保证,如果没有某种形式的同步,它也不会对执行顺序产生任何可重复的影响。
-
@Baldy 我想避免过多介绍细节,但是每个线程都有一个随机数据生成器,我需要确保该过程是可重复的。假设我需要提供它们处理的线程和数据的组合是可重复的。
-
@Kylar 你的想法确实没有那么不好,但是它不能很好地概括。
-
@voo 你需要你的第一个任务在你的第一个线程上运行,而不是别的,还是你还需要第 2 个任务来在一个特定的线程上执行,等等?
标签: java multithreading concurrency executorservice