【问题标题】:Java ExecutorService and updating a commonly used ressourceJava ExecutorService 和更新一个常用的资源
【发布时间】: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


【解决方案1】:

您正计划进行顺序处理,因此即使您使用线程......第二个线程也无法与第一个线程并行处理,因为 它正在等待第一个终止。 也许您可以查看线程的连接功能,其中连接创建一个线程 等待另一个线程完成执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2020-01-17
    • 2020-09-21
    • 2017-09-21
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多