【发布时间】:2018-07-19 10:34:18
【问题描述】:
我有一个包含 10 个元素的 ArrayList。我启动了一个大小为 10 的线程池,并使用传递给每个线程的元素调用执行。每个线程将该元素作为输入进行一些处理并输出结果。问题是,输出有时只有 7 个元素的处理结果,有时有 8 个元素,有时有一些重复,有时有 9 个元素。我不确定为什么我没有正好 10 个元素的处理结果。这是我的代码sn-p。
ExecutorService exeSvc =
Executors.newFixedThreadPool(10)
for (Object element: arlList)//arlList is the arraylist of
size-10
{
exeSvc.execute({->myRunnable element});
}
我做错了什么?
【问题讨论】:
-
如果可能的话,你能添加输出吗?
-
如果一个线程完成了一项工作,它会立即执行下一个工作,所以有时第一个线程会在最后一个线程创建之前完成 2 个工作。这就是你有重复的原因。
-
"
exeSvc.execute({->myRunnable element});" - 这不会编译。 -
试试这样的
for (Object element: arlList) { Runnable worker = new WorkerThread(); executor.execute(worker); } executor.shutdown(); -
1.为什么它被标记为
groovy? 2. 在for中声明局部变量为element变量的副本,并使用execute({})中的副本。 3.使用execSvc.shutdown() && awaitTermination()等待所有执行完成
标签: java multithreading groovy threadpool threadpoolexecutor