1. Four solutions to task code throwing exceptions:

  • Catch any exceptions that the task code might throw, including undetected exceptions, in the Runnable run method we provide
  • Use the ExecutorService. Submit a mission, the use of object back to the Future of the get method receives the exception thrown, then processing (using Java. Util. Concurrent. FutureTask packaging, realize the call)
  • Rewrite the ThreadPoolExecutor afterExecute method, processing to the afterExecute method of anomaly
  • Set UncaughtExceptionHandler for the worker thread to handle exceptions in the uncaughtException method

Note that when using this last scenario, you cannot process tasks submitted in the form of submit

1.1 the first kind of source code: exceptions will cause the thread to die, create a new worker to join the thread pool

1.2 Second source code: the worker thread is the same, except that the run method executes a Future object with a life cycle, so the worker is not created multiple times

Packaged by FutureTask! public FutureTask(Runnable runnable, V result) { this.callable = Executors.callable(runnable, result); this.state = NEW; // ensure visibility of callable }Copy the code