An overview of the
Basic composition of a thread pool: N threads (thread pool), N tasks (task queue)
thread
Thread storage
A thread pool must contain threads, represented in ThreadPoolExecutor as the internal worker class; The relationship between threads and workers is one-to-one; And is an implementation of AQS, or a RunnableThreadPoolExecutor requires a bunch of threads stored in a HashSet property called workers
Thread creation
ThreadFactory’s newThread method is used in the worker constructor to get threads;
The specific creation logic is in the class that implements the ThreadFactory interface; eg: DefaultThreadFactory
The worker is created in the addWorker method and executes the thread
Line 1 retry: Referencewww.cnblogs.com/captainad/p…
Thread execution
Thread pool execution is implemented using the Execute method of the Executor interface. The ThreadPoolExecutor hierarchy is at the top of the Executor hierarchy and implements the execute method, which calls the addWorker method, so the Thread is actually executed by the addWorker method, which uses the start method of Thread
How are tasks and threads assembled?
The thread is already tied to the task when it is created, but the run method can call other Runnable run methods (or custom methods).
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("The thread is already tied to the task when it is created.");
});
thread.start();
}
Copy the code
ThreadPoolExecutor does the following
- The ThreadPoolExecutor worker contains a task taken from a task queue.
- The worker itself is also a task Runnable
- When a thread executes worker’s run method, the worker’s run method calls its own Runnable run method
The pseudocode is as follows
/** * worker */
public class Worker implements Runnable {
// The real task
Runnable task;
public Worker(Runnable runnable) {
this.task = runnable;
}
public static void main(String[] args) {
Thread thread = new Thread(new Worker(() -> {
System.out.println("Task run method");
}));
thread.start();
}
@Override
public void run(a) {
System.out.println("Worker's run method");
runWorker();
}
private void runWorker(a) {
this.task.run(); }}Copy the code