Java thread pool Threadpoolexecutor is very common and is commonly constructed as follows:
Public Threadpoolexecutor (intCorepoolsize,int Maximumpoolsize, long KeepAliveTime, timeunit unit, blockingqueue WorkQueue, Rejectedexecutionhandler handler) { this (Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, Executors.defaultthreadfactory (), handler); }
- Corepoolsize: Thread pool maintains a minimum number of threads
- maximumpoolsize: Maximum number of threads maintained by the thread pool
- keepalivetime: The thread pool maintains idle time allowed by threads
-
- workqueue: Buffer queue used by thread pool
- handler: Thread pool processing policy for rejected tasks
A maximum buffer queue capacity is typically set in formal use, and if the thread pool is full it executes the specified deny policy on the task thread that continues to be added, the last parameter of Threadpoolexcetor specifies the deny policy, and the JDK provides four rejection policies:
AbortPolicy policies, callerrunspolicy policies, discardoledestpolicy policies, discardpolicy policies.
AbortPolicy policy: This policy throws an exception directly, preventing the system from working properly.
Callerrunspolicy policy: As long as the thread pool is not closed, the policy runs the current discarded task directly in the caller's thread.
Discardoleddestpolicy policy: This policy discards the oldest request, the task that is about to be executed, and attempts to commit the current task again.
Discardpolicy policy: This policy silently discards the tasks that cannot be handled, without any processing.
You can see that the four policies provided by default do not seem to be very friendly, either give up or throw an exception, sometimes we need to ensure that the task add does not fail, as long as the added task can be executed sequentially in order, do not need this add action immediately response,
That is, to have the thread pool wait for the tasks in the pool to complete before adding new tasks, you need to customize the Deny policy and the task buffer queue with the following code:
Package Com.montnets.task;import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.rejectedexecutionhandler;import Java.util.concurrent.threadfactory;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.timeunit;import Java.util.concurrent.atomic.AtomicInteger;/** * Custom blocking thread pool blocking task submission when China * * @ClassName: Blockthreadpool * @Description: TODO * @author: Wangs * @date: 2018-1-24 PM 5:24:54*/ Public classBlockthreadpool {PrivateThreadpoolexecutor pool =NULL; PublicBlockthreadpool (intpoolsize) {Pool=NewThreadpoolexecutor (Poolsize, Poolsize,0, Timeunit.milliseconds,NewArrayblockingqueue<runnable> (5),Newcustomthreadfactory (),NewCustomrejectedexecutionhandler ()); } Public voiddestory () {if(Pool! =NULL) {Pool.shutdownnow (); } } Private classCustomthreadfactory implements Threadfactory {PrivateAtomicinteger count =NewAtomicinteger (0); @Override Publicthread Newthread (Runnable r) {thread T=NewThread (R); String ThreadName= Blockthreadpool.class. Getsimplename () + Count.addandget (1); T.setname (ThreadName); returnT; } } Private classCustomrejectedexecutionhandler implements Rejectedexecutionhandler {@Override Public voidRejectedexecution (Runnable R, Threadpoolexecutor executor) {Try { //core transformation point, changed from Blockingqueue's offer to put blocking methodExecutor.getqueue (). put (R); } Catch(interruptedexception e) {e.printstacktrace (); } } } Public voidExecute (Runnable Runnable) { This. Pool.execute (runnable); } //test the constructed thread pool Public Static voidMain (string[] args) {Blockthreadpool pool=NewBlockthreadpool (3); for(inti =1; I < -; i++) {System. out. println ("submission of paragraph"+ i +"a mission!"); Pool.execute (NewRunnable () {@Override Public voidrun () {Try{System. out. println (Thread.CurrentThread (). GetId () +"===== Start"); TimeUnit.SECONDS.sleep (Ten); System. out. println (Thread.CurrentThread (). GetId () +"===== "End""); } Catch(interruptedexception e) {e.printstacktrace (); } } }); System. out. println ("the submission of the first"+ i +"a successful mission! ""); } //2. Destruction----cannot be destroyed here because the task is not completed and the task cannot be executed if the thread pool is destroyed//exec.destory (); Try{Thread.Sleep (10000); } Catch(interruptedexception e) {e.printstacktrace (); } }}
The core implementation of this class is threadpoolexecutor, but the Customrejectedexecutionhandlerof the Deny policy is customized, and the buffer queue is modified to Arrayblockingqueue. The blocking function is implemented,
When the core pool and cache queue are full, the external call to execute is blocked until the idle thread is freed after a task in the pool has been completed, and the task is added to the cache queue without throwing an exception or discarding the task.
Suitable for some scheduled scan triggering task class scenarios.
Love why love, careless How to heart, empty know people's wisdom, hate without self-knowledge.
Java Custom blocking thread pool