This is the 22nd day of my participation in the August Wen Challenge.More challenges in August

Submit tasks to the thread pool

You can submit tasks to the thread pool using two methods, the execute() and submit() methods.

The execute() method is used to submit tasks that do not require a return value, so there is no way to determine whether the task was successfully executed by the thread pool. The following code shows that the task entered by the execute() method is an instance of the Runnable class.

threadPool.execute(new Runnable() {
    @Override
    public void run(a) {}});Copy the code

The submit() method is used to submit tasks that require a return value. The thread pool returns an object of type Future that determines whether the task was successfully executed, and the return value can be retrieved from the Future’s get() method. The get() method blocks the current thread until the task is complete. Instead, get(long timeout, The TimeUnit unit method blocks the current thread for a while and then returns immediately, possibly without completing the task.

Future<Object> future = threadPool.submit(harReturnValuetask);
try {
    Object s = future.get();
} catch (InterruptedException e) {
    // Handle the interrupt exception
} catch (ExecutionException e) {
    // Handle the exception that tasks cannot be executed
} finally {
    // Close the thread pool
    threadPool.shutdown();
}
Copy the code

Closing the thread pool

A thread pool can be shutdown by calling its shutdown or shutdownNow methods. They work by iterating through worker threads in a thread pool and then interrupting them by calling the thread_by-thread_interrupt method, so tasks that cannot respond to interrupts may never be terminated.

ShutdownNow first sets the state of the thread pool to STOP, then tries to STOP all threads executing or suspending tasks and returns the list of tasks waiting to be executed, while shutdown only sets the state of the thread pool to shutdown. It then interrupts all threads that are not executing tasks.

The isShutdown method returns true whenever either of the two shutdown methods is called. The thread pool is closed successfully when all tasks are closed, and calling isTerminaed returns true. Which method should be called to shutdown the thread pool depends on the nature of the task submitted to the pool. The shutdown method is usually called to shutdown the thread pool, or the shutdownNow method can be called if the task is not necessarily finished.