如果线程失败,函数必须 return 为真

Function must return true if thread fails

我有一个函数可以做一些工作,如果它失败或有异常,它 return 是正确的。 现在我在这个函数中创建了一个线程,负责做同样的工作。现在,如果线程正在执行此任务时抛出某些异常,我如何使函数 return 为真?

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

您可以通过以 Callable instead of Runnable. Unlike Runnable, Callable allows you to return some result to the code that invokes it in form of 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 article and JavaDocs for Callable, Future and ExecutorService 类。