A, Thread
Threads are the foundation of concurrent programming and the smallest unit of program execution
There are six states of Thread:
- NEW: the NEW state is not started
- RUNNABLE: Ready state, indicating that it is runable. It may be running or queuing for CPU allocation by the operating system
- BLOCKED:Blocked state waiting for a lock to execute
synchronized
methods - WAITING:Wait state due to call
Object.wait(), thread.join (), locksupport.park ()
One of the - TIMED_WAITING: timed wait state with a specified amount of time longer than the wait state
- TERMINATED: indicates that the thread is TERMINATED
Thread common methods:
Thread.join() : When other.join() is called in a Thread, the current Thread cedes execution authority to the other Thread until the other Thread finishes executing or reaches a specified time
Thread.yield() : indicates that the Thread scheduler is given a hint that the current Thread is willing to surrender CPU, but the Thread scheduler may ignore this hint
Second, the ThreadPoolExecutor
Thread pooling is a pooling technique designed to avoid the performance cost of frequent thread creation and destruction
According to The Java Development Manual of Alibaba, thread pools are not allowed to be created by Executors. Instead, create thread pools through ThreadPoolExecutor
Executors create thread pool object pros:
-
FixedThreadPool and SingleThreadPool: Allows the request queue length to be integer. MAX_VALUE
-
CachedThreadPool and ScheduledThreadPool: Allows the number of threads to be created as Integer.MAXVALUE, which may create a large number of threads and result in OOM
ThreadPoolExecutor constructor argument:
- CorePoolSize: The number of core threads that will reside in the thread pool without tasks
- MaximumPoolSize: maximum number of threads allowed in the thread pool
- KeepAliveTime: The time to wait before destruction when a non-core thread is idle
- Unit: time unit
- WorkQueue: indicates a task queue that stores only the tasks submitted by the execute method
- ThreadFactory: threadFactory, used to create new threads
- RejectedExecutionHandler: Reject the policy when the task queue is full and new threads cannot be created
Execute rules
If the thread count is less than the core number of threads, directly to create a new thread to perform a task If the number of threads is equal to or greater than the core number of threads, try to insert task task queue If you can’t insert task queue, and the number of threads have not reached the maximum number of threads, create a new thread to perform a task If has reached the maximum number of threads, the implementation of rejection policies