What is a thread pool:
A thread pool is a pool of control threads. Used to control the number of threads.
Why to use the thread pool:
1. Prevent the system from repeatedly creating and destroying threads that affect the run time (create + Destroy >> Execute time)
2. Control the number of threads, too many threads will cause the machine to run the card (approximately one thread occupies 1M space)
Threadpoolexecutor Construction Method
Public threadpoolexecutor (int corepoolsize, int maximumpoolsize, long keepalivetime, timeunit unit, Blockingqueue<ru Nnable> workQueue)
Parameter 1: Core thread pool size (standard size)
Parameter 2: Maximum thread pool size
Parameter 3: Set how long time-out recycles threads
Parameter 4: Is an enumeration that represents the units of the KeepAliveTime
Parameter 5: Queue to hold tasks
Instance
public class Threadpoolexecutordemo {public static void main (string[] args) {//linkedblockingdeque thread queue size is unlimited, Does not throw an exception blockingqueue<runnable> queue = new linkedblockingdeque<runnable> ();//If the core thread and the maximum thread are the same, Then the thread is a fixed-size thread pool. Threadpoolexecutor executor = new Threadpoolexecutor (3, 6, 1, timeunit.days, queue); for (int i=0;i<20;i++) { Executor.execute (New Runnable () {@Overridepublic void run () {try {thread.sleep ()} catch (Interruptedexception e) {E . Printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName ());}); System.out.println ("-----------------------------------------------"); for (int i=0;i<20;i++) {Executor.submit ( New Runnable () {@Overridepublic void run () {System.out.println (Thread.CurrentThread (). GetName ());}}); Executor.shutdown ();}}
The thread pool makes the following judgments when executing threads:
1. If the number of threads is less than the core thread, create and execute this County
2. If the number of threads is greater than the core thread, put in the queue
3. If the queue is full and is less than the maximum number of threads, create the execution of this thread
4. If the queue is full and is larger than the maximum number of threads, throw an exception.
When the thread is idle, exceeds the recycle time, and the number of thread pools is greater than the number of cores, it is recycled until the number of core threads is returned
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java thread pool Threadpoolexecutor simple Application