【问题标题】:Executor Service with void return type返回类型为 void 的执行器服务
【发布时间】:2019-02-06 11:57:44
【问题描述】:

这里我想调用n线程并执行我的函数padrDao.saveGuidanceDetails(sgd),这是一个执行插入操作的DAO方法并返回一个long值,如下面的代码所示。

我正在使用 Callable,但它要求我返回一些值,但我不熟悉使用 Runnable 进行相同工作的线程。有人可以验证代码是否正确或要进行任何修改吗?我觉得代码是错误的,因为在 callable 中有一个 return 语句,这将把我带到第一个任务本身的 main 方法之外。

int totalThreadsNeeded=listForguidanceItems.size();     
ExecutorService executor = Executors.newFixedThreadPool(totalThreadsNeeded);
List<Callable<Void>> runnableTasks = new ArrayList<>();
final PriceLineItemsResultExt response1=response;

for(final ProductLineItemResultExt item: listForguidanceItems)
{
    int counter=0;
    final SavedGuidanceDetailsDto sgd=list.get(counter);

    Callable<Void> task1 = new Callable() {
        public Void call() {
            if (sgd.hasGuidance())
            {
                if (response1.isSaveGuidance()) {
                    long guidanceDetailsId = padrDao.saveGuidanceDetails(sgd);
                    item.setGuidanceDetailsId(String.valueOf(guidanceDetailsId));
            } 
        }

        return null;
    }};

    counter++;
    runnableTasks.add(task1);
}

try {
    executor.invokeAll(runnableTasks);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    logger.info("Thread fail exception  " + e);
}

executor.shutdown();

请建议我使用正确的代码进行修改?在此先感谢

【问题讨论】:

    标签: runnable executorservice java-threads callable


    【解决方案1】:

    要使用 Runnable,您可以简单地替换这些:

    Callable<Void> task1 = new Callable() {
            public Void call() {
    ...
    

    Runnable task1 = new Runnable {
      public void run() {
    ...
    

    使用 runnable 你就不必返回任何东西了。

    当然,如果您仍想将它们存储在 Collection 中(可能不是),您还需要将 runnableTasks 修改为 List&lt;Runnable&gt;,并更改您在 ExecutorService 中提交它们的方式:

    executor.submit(your_Runnable_object)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-23
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 2015-03-24
      • 2010-12-24
      相关资源
      最近更新 更多