Thread Pool
Effect of contrast
- Common thread startup mode
- Use thread pool threads started way
Introduction thread pool
- Reduce resource consumption: do not create frequent destruction of resources.
- Improve response time
- Thread improve manageability
Simple thread pool design
Design ideas
The design process need to think about
- The initial number of threads created
- Not available threads resolution strategy
- Buffer array length
- Buffer array full of how to do?
The core argument of the thread pool
- corePoolSize
- maxiumPoolSize
- keepAliveTime
- unit
- workQueue
- threadFactory
- handle
Thread pool process flow
Blocking queue
- Unbounded queue (list)
- Bounded queue (linked lists, arrays)
- Synchronous transfer queue
Optional thread pool saturation strategy
- AbortPolicy termination policy (default): Throws, reject the new task
- DiscardPolicy abandon the strategy: to abandon the new task
- DiscardOldestPolicy abandon the old mission strategy: throw away the oldest tasks, add new tasks
- Submitted by a party to perform the operation tasks: Policy CallerRunsPolicy caller running
Schematic execution thread pool
Common thread pool
Executors.newSingleThreadExecutor() //单一线程线程池
Executors.newCachedThreadPool() //线程数量无限线程池
Executors.newFixedThreadPool( 10 ) //线程数量固定的线程池
Submit jobs to the thread pool in two ways
- submit()
- execute () can not return a value to the main thread
Thread pool status
- RUNNING
- SHUTDOWN
- STOP
- TIDYING
- TERMINATED