Why use a thread pool?
- 1. Create/Destroy threads with overhead, creating/destroying threads too often can affect the efficiency of the Office to a great extent
- 2. Excessive number of threads, preemption of system resources causing blocking
- 3. Some simple management of the thread
In Java, the thread pool concept is executor this interface, specifically implemented as the Threadpoolexecutor class, learning Java in the thread pool, you can directly learn his configuration of the thread pool, Is the configuration of the parameters of the Threadpoolexecutor constructor
First, Threadpoolexecutor provides four constructors:
Constructor for five parametersPublicThreadpoolexecutor(int Corepoolsize,int Maximumpoolsize,Long KeepAliveTime, timeunit unit, blockingqueue<runnable> WorkQueue)Six parameters of the constructor-1PublicThreadpoolexecutor(int Corepoolsize,int Maximumpoolsize,Long KeepAliveTime, timeunit unit, blockingqueue<runnable> WorkQueue, Threadfactory threadfactory)//Six parameters for constructors-2 public threadpoolexecutor(int corepoolsize, int maximumpoolsize, long KeepAliveTime, Timeunit unit, blockingqueue<runnable> WorkQueue, Rejectedexecutionhandler handler)// Constructor for seven parameters public threadpoolexecutor(int corepoolsize, int maximumpoolsize, long KeepAliveTime, Timeunit unit, blockingqueue<runnable> WorkQueue, Threadfactory threadfactory, Rejectedexecutionhandler handler)
The following parameters are explained below:
- int corepoolsize: Maximum number of core threads in this thread pool
Core Thread: when the thread pool creates new threads, if the total number of current threads is less than corepoolsize, a new core thread is created, and if Corepoolsize is exceeded, the newly created non-core thread core thread will remain alive by default in the inline pool. Even if the core thread is doing nothing (idle).
If you specify Threadpoolexecutor's Allowcorethreadtimeout This property is true, the core thread will be destroyed if it is not working (idle) for a certain amount of time (as determined by the parameters below).
- int maximumpoolsize: Maximum number of threads in this thread pool
Total Threads = Number of core threads + non-core threads.
- Long KeepAliveTime: non-core thread idle timeout length in this thread pool
A non-core thread that will be destroyed if it does not work (idle) longer than the length set by this parameter, if set allowcorethreadtimeout = True, it will act on the core thread.
- timeunit Unit:units of KeepAliveTime
Timeunit is an enumeration type that includes:
Nanoseconds:1 Micro-millisecond = 1 microseconds/1000
Microseconds:1 microseconds = 1 ms/1000
Milliseconds:1 ms = 1 sec/1000
SECONDS: Sec
MINUTES: Min
HOURS: Hours
Days: Day
- blockingqueue workQueue: task queue in this thread pool: maintaining Runnable objects waiting to be executed
When all the core threads are working, the newly added task is added to the queue for processing, and if the queue is full, a new non-core thread executes the task.
Common Types of Workqueue:
-
synchronousqueue : When this queue receives a task, it is submitted directly to the thread processing, without preserving it, what if all the threads are working? Then create a new thread to handle this task! So in order to ensure that the number of < threads does not come up to maximumpoolsize and cannot create a new thread > error, when using this type of queue, Maximumpoolsize is generally specified as Integer.max_value, which is infinitely large
-
linkedblockingqueue : When this queue receives a task, the new thread (core thread) processes the task if the current number of threads is less than the number of core threads, and if the current number of threads equals the number of core threads, Wait for the queue to enter. Since this queue does not have a maximum limit, all tasks that exceed the number of core threads are added to the queue, which results in the maximumpoolsize setting being invalidated because the number of bus threads never exceeds corepoolsize
-
Arrayblockingqueue : You can limit the length of a queue, when you receive a task, if you do not reach the Corepoolsize value, the new thread (core thread) executes the task, and if it is reached, queue up and wait if it is full , the new thread (non-core thread) performs the task, and if the number of bus threads is maximumpoolsize and the queue is full, an error occurs
-
delayqueue : The elements in the queue must implement the delayed interface, which means that the task you pass in must first implement the delayed interface. When this queue receives a task, it first queues up, and only the specified delay time is reached to perform the task
-
threadfactory threadfactory: How to create a thread, which is an interface , you need to implement his thread newthread (Runnable R) method when you new him, generally not.
-
Rejectedexecutionhandler handler: this thing is to throw the exception-specific, such as the above mentioned two error occurred, will be thrown by this handler an exception , it is not used at all.
Ii. adding tasks to Threadpoolexecutor
How do we know the new one threadpoolexecutor, probably know what each parameter is, but I am new, how to submit a task to the thread pool to perform?
command)
You can add a task to the thread pool by using the Threadpoolexecutor.execute (Runnable command) method.
Three, the strategy of Threadpoolexecutor
To summarize here, when a task is added to the thread pool, the policy is executed:
- 1. If the number of threads does not reach corepoolsize, create a new thread (core thread) to perform the task
- 2. When the number of threads reaches Corepools, the task is moved into the queue waiting
- 3. The queue is full, new threads (non-core threads) Perform tasks
- 4. When the queue is full and the number of bus threads reaches Maximumpoolsize, an exception is thrown by (Rejectedexecutionhandler)
+++++++++++++++++++++++++++ I'm a split line ++++++++++++++++++++++++++++
Four types of thread pools are common:
If you don't want to write a thread pool yourself, Java provides four thread pools through executors, and these four thread pools are implemented directly or indirectly by configuring Threadpoolexecutor parameters.
1. cacheable thread pool Cachedthreadpool ()
Source:
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
According to the source code can be seen:
- There is no core thread inside this thread pool, there is no limit to the number of threads.
- When the task is created, the idle thread is reused if there is an idle thread, and if not, the new thread.
- A thread that is not working (idle) will be destroyed if it does not work more than 60S.
To create a method:
ExecutorService mCachedThreadPool = Executors.newCachedThreadPool();
Usage:
Start downloadPrivatevoidStartdownload(Final ProgressBar ProgressBar,Finalint i) {Mcachedthreadpool.execute (New Runnable () {@OverridePublicvoidrun () {int p = 0 Progressbar.setmax (10); while (P < 10) {p++; progressbar.setprogress (P); Bundle bundle = new bundle (); Message message = new message (); Bundle.putint ( "P", p); //the name of the current thread handler let TextView show bundle.putstring ( "ThreadName", Thread.CurrentThread (). GetName ()); Message.what = i; Message.setdata (bundle); Mhandler.sendmessage (message); try {thread.sleep (1000);} catch (interruptedexception e) {e.printstacktrace ();}} } }); }
2.FixedThreadPool Fixed-line pool
Source:
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());}
According to the source code can be seen:
- The maximum number of threads in the thread pool equals the number of core threads, so by default the thread pool's threads are not destroyed because of idle state timeouts.
- If the current number of threads is less than the number of core threads and there are idle threads to submit the task, then the unused threads are not reused, and new threads are created to perform the task. If the number of currently executing tasks is greater than the number of core threads, the larger portion goes into the queue waiting. Waiting for idle threads to perform this task.
To create a method:
//nThreads => 最大线程数即maximumPoolSizeExecutorService mFixedThreadPool= Executors.newFixedThreadPool(int nThreads);//threadFactory => 创建线程的方法,用得少ExecutorService mFixedThreadPool= Executors.newFixedThreadPool(int nThreads, ThreadFactory threadFactory);
Usage:
private void startDownload(final ProgressBar progressBar, final int i) { mFixedThreadPool.execute(new Runnable() { @Override public void run() { //....逻辑代码自己控制 } }); }
3.SingleThreadPool
Source:
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));}
According to the source code can be seen:
- There is only one worker thread that performs the task
- All tasks are executed in the specified order, that is, following the queued rules of the queue
To create a method:
Executorservice Msinglethreadpool = Executors.newsinglethreadpool ();
Usage Ibid.
4.ScheduledThreadPool
Source:
public static scheduledexecutorservice newscheduledthreadpool (int corepoolsize) {return new scheduledthreadpoolexecutor (corepoolsize);} //scheduledthreadpoolexecutor (): Public scheduledthreadpoolexecutor ( int corepoolsize) {super (Corepoolsize, Integer.max_value, Default_keepalive_millis, MILLISECONDS, new Delayedworkqueue ()}
According to the source code can be seen:
Default_keepalive_millis is the default 10L, this is 10 seconds. This thread pool is kind of like, isn't it? Cachedthreadpool and Fixedthreadpool combined a bit.
- Not only the number of core threads is set, but the maximum number of threads is also integer.max_value.
- This thread pool is the only one in the 4 above that has deferred execution and periodic execution tasks.
Create:
//nThreads => 最大线程数即maximumPoolSizeExecutorService mScheduledThreadPool = Executors.newScheduledThreadPool(int corePoolSize);
The general method of executing tasks is similar to the above, and we mainly look at the methods of delaying the execution of tasks and performing tasks on a periodic cycle.
//means that we begin to perform our task in 3 seconds. Mscheduledthreadpool.schedule (new Runnable () { @Override public void run () {//...}}, 3, timeunit.seconds)
//delay after 3 seconds to execute the task, starting from the start of the task this time to start timing, Executes every 7 seconds regardless of how long it takes to perform the task. Mscheduledthreadpool.scheduleatfixedrate (new Runnable () {@O Verride public void run () {//...}}, 3, 7, timeunit.seconds);
/**延迟3秒后执行任务,从任务完成时这个时候开始计时,7秒后再执行,*再等完成后计时7秒再执行也就是说这里的循环执行任务的时间点是*从上一个任务完成的时候。*/mScheduledThreadPool.scheduleWithFixedDelay(new Runnable() { @Override public void run() { //.... } },3, 7, TimeUnit.SECONDS);
These are the four thread pools that are commonly used and their implementation principles.
My brother is a programmer.
Links: https://www.jianshu.com/p/ae67972d1156
Source: Pinterest
The copyright of the book is owned by the author, and any form of reprint should be contacted by the author for authorization and attribution.
Java common four thread pool usage and threadpoolexecutor detailed