This article explores what happens when a task is submitted in ThreadPoolExecutor and the generation of the future callback function.
As shown in the above figure, after the submission, it first enters this code block, where two tasks are mainly executed: creating a RunnableFuture object and starting a thread to execute the RunnableFuture.
Next, let's go to the first line of the core code, as shown below, where a FutureTask object is created.
The most important member variables of the FutureTask object are as follows:
Next, let's go to the second line of the core code, which is essentially starting a thread and executing:
Next, let's consider how Java uses future.get() and future.cancel() to start or cancel a task.
First, let's look at the future.get() method:
So where does the outcome come from? Of course, it comes from the run method in FutureTask, which assigns the result of the task to the outcome member variable.
As for the future.cancel() method, it sets the thread to an interrupted state to cancel the task: