【问题标题】:Function must return true if thread fails如果线程失败,函数必须返回 true
【发布时间】:2017-09-27 11:01:48
【问题描述】:

我有一个函数可以完成一些工作,如果它失败或有异常,它会返回 true。 现在我在这个函数中创建一个线程,负责做同样的工作。现在,如果线程执行此任务时抛出一些异常,我该如何让函数返回 true?

   boolean read(){   
      service.execute(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                //does the required work.
      });
   }

【问题讨论】:

  • 请标记编程语言

标签: java multithreading exception-handling return-value


【解决方案1】:

您可以通过以Callable 而不是Runnable 的形式提供要由新线程执行的逻辑来实现此目的。与Runnable 不同,Callable 允许您以Future 的形式将一些结果返回给调用它的代码。

boolean read() {   
   Future<Boolean> future = service.submit(() -> {
      // Do your calculations and return whatever is required
      return true;
   });

  // future.get() blocks current thread execution until Callable returns the result
  return future.get();
}

我还建议阅读ThreadPoolExecutor + Callable + Future Example 文章和CallableFutureExecutorService 类的JavaDocs。

【讨论】:

    猜你喜欢
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-23
    相关资源
    最近更新 更多