我正在尝试在一个数据数组上实现一个繁重的计算过程。
为此,我使用了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的多线程能力的同时做到这一点呢?
发布于 2015-05-11 20:37:20
您计划进行顺序处理,因此即使您使用的是threads..the,第二个线程也不能并行处理第一个线程,因为它正在等待第一个线程终止。也许你可以研究一下线程的联接特性,在这个特性中,联接使一个线程等待另一个线程完成执行。
https://stackoverflow.com/questions/30147538
复制相似问题