The running status of the thread

Each time we create a thread for the JVM, a thread is bound to the JVM thread in the kernel space thread table

Coroutines (fibers, user-level threads)

The system thread switches fibers to squeeze as much CPU as possible

The thread pool

ThreadPoolExecutor

If the number of concurrent requests is very large, but the execution time of each thread is very short, threads will be created and destroyed frequently, which will greatly reduce the efficiency of the system. It may appear that the server is creating a new thread and destruction line for each request, or it may even execute the task for less time than it took to create the thread pool

Int corePoolSize Number of core threads int maxmunPoolSize Maximum number of threads = non-core threads + number of core threads int KeepAliveTime Maximum number of idle threads TimeUnit Unit of time BlockingQueue<Runnable> workQueue Tasks to store unfinished tasks ThreadFactory ThreadFactory Factory for creating threads RejectedExecutionHandler Handler Rejection policiesCopy the code

1. The first step is to submit the task to the thread pool using the execute method. If there are no threads in the thread pool, the core thread will be created first and the task will be put into the core thread 2. Step 2 When the core thread >=5, put the task in the blocking queue 3. Step 3 Put the task in the non-core thread, create the non-core thread full 4. Step 4 If the maximum number of threads are full to reject the policyCopy the code

The source code parsing

1. WorkerCountOf (c) get the current number of threads Add (w) add(w) add(w) add(w) add(w) add(w) add(w) add(w) add(w) add(w) add(w) add(w) RunWorker (this) calls the runWorker() method of the external class 2.5.task.run() to perform the task 2.6.gettask (). 3. IsRunning (recheck) Checks whether the current thread pool life state still exists 4. Offer (command) Puts the task on the queue 5. Reject (command) 6.1.AbortPolicy Discard exception 6.2.CallerRunsPolicy If the current thread pool is not closed, the thread that submitted the task executes the task directly DiscardOldestPolicy: Removes a task from the current queue and installs the current task into the queue leaderCopy the code

Thread pool parameter Settings:

CPU intensive: number of CPU cores +1 IO intensive :2cpu Hertz +1

rocketmq,eureka,nacos 2cpu

State transitions

shutdown(); running->shutdown

shutdownNow(); running->stop

ScheduledThreadPoolExecutor

Usage scenario: Distributed lock -reids

If (setnx(“”))

park,sleep

}

Timer: single thread. The thread hangs and no longer executes the task

ScheduledThreadPoolExecutor thread pool (timing) : thread hanging, in submitting, thread pool will also create new threads to perform a task

Xxl-job: scheduled task + distributed scheduling

Quartz: Single machine timing task, powerful function

Elastic-Job