【发布时间】:2017-05-22 10:33:32
【问题描述】:
-
我有一个需要在 for 循环中处理的 40000 条记录的列表。因为我有两个处理器系统。我创建了一个这样的固定线程池:
int threads = Runtime.getRuntime().availableProcessors(); ExecutorService service = Executors.newFixedThreadPool(threads); 并将我的
ArrayList分成两个子列表。对于每个子列表,我创建了一个Callable,它执行相同的功能(涉及迭代子列表并进行一些处理)并返回一个Future对象。我使用
executorServiceObject.submit(callable)提交了这两个Callable,并将返回的Future对象添加到我的Future对象列表中
这是我的问题:
我写了System.Out.printLn("Processed Item" +item.id) // consider item as the name of reference variable for current iteration
一段时间以来一切都很好,我可以看到两个线程同时工作。但一段时间后,其中一个线程已停止处理。只有一个线程在运行。 (我知道这一点是因为我可以在控制台上看到不再打印给线程 2 的 id)。
有人知道这是怎么回事吗?我的意思是为什么 ExecutorService 停止运行第二个线程。
提前感谢您的帮助。
按照我之前应该做的那样添加示例代码:
public List<Output> processInputs(List<Input> inputs)
throws InterruptedException, ExecutionException {
int threads = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(threads);
List<Future<Output>> futures = new ArrayList<Future<Output>>();
for (final Input input : inputs) {
Callable<Output> callable = new Callable<Output>() {
public Output call() throws Exception {
Output output = new Output();
// process your input here and compute the output
return output;
}
};
futures.add(service.submit(callable));
}
service.shutdown();
List<Output> outputs = new ArrayList<Output>();
for (Future<Output> future : futures) {
outputs.add(future.get());
}
return outputs;
【问题讨论】:
-
请edit您的问题包含您程序中的相关代码。理想情况下,您应该包含一个重现问题的minimal reproducible example。
-
这可能实际上并没有停止。它可能处于等待状态。检查非工作线程的run方法,看看最后执行的是哪一行。
-
@pikrut 我使用了 'Callable' 所以没有 run() 方法。其次,Callable 是在 for 循环中创建的(1 个可调用的 1 个子列表)。这意味着两个子列表的调用方法实现相同
-
@Kenster:对不起,我现在添加了示例代码。我在我的代码中提到了一条评论,这意味着我正在迭代我的子列表并进行一些处理。
标签: java multithreading concurrency executorservice java.util.concurrent