【发布时间】:2015-05-10 03:50:25
【问题描述】:
我正在尝试在数据数组上实现繁重的计算过程。
为此,我使用 Executor 服务来获取每个处理的结果,同时充分利用 CPU 的全部功能。
但是,我需要将我从先前执行的线程中获得的结果提供给在数组上工作的下一个线程,而不必等待所有线程终止。
通过其他术语,shared_ressource 数组是所有 DATAItem 对象的公共属性,并且由每个线程(DATAItem 对象)修改。
我希望 for 循环中的下一个 DATAItem 对象可以使用线程感知修改(此处由 While 循环替换)。
int np = Runtime.getRuntime().availableProcessors();
ExecutorService pool = new ThreadPoolExecutor(np-2, np-2, 5000,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
// shared_ressource is the array of objects from class SharedRessource to be modified by each thread
int i = 0;
while (i<shared_ressource.size())
{
if (((ThreadPoolExecutor) pool).getActiveCount()<=(np-2) )
{
DATAItem di = new DATAItem();
di.setSharedRessource(shared_ressource);
Future<List<SharedRessource>> DataItemMod = pool.submit(di);
// the Future's .get() method returns the modified shared_ressource array
i++;
}
else
try {Thread.sleep(100);}
catch (InterruptedException e) {e.printStackTrace();}
}
pool.shutdown();
这可能吗?
否则,我怎么能在受益于完整 CPU 的多线程能力的同时做到这一点?
【问题讨论】:
-
您对问题的描述需要改进。不清楚你是如何分工的。
-
@Daniel Sperry 我应该具体解释什么?
-
每个 DATAItem(我想它是可调用的)究竟是如何修改原始数组的?到位?创建一个带有一些额外元素的新数组?如果它真的在原地修改了原始数组,那么如何防止弄乱其他 DATAItems 的输入?也许描述你的实际问题会有所帮助。
标签: java multithreading data-processing