Creating a thread pool from executor
Executor.newfixedtreadpool
Public Static Executorservice newfixedthreadpool (int nthreads) { returnnew Threadpoolexecutor (Nthreads, nthreads, 0L, timeunit.milliseconds, new Linkedblockingqueue<runnable>()); }
Internal create thread pool from new Threadpoolexecutor
Returns a fixed number of thread pools. If there is an idle thread in the thread pool, it is delivered directly to the idle thread. If the task is not placed in the queue
Executor.newsinglethreadexecutor
Public Static Executorservice Newsinglethreadexecutor () { returnnew Finalizabledelegatedexecutorservice (new threadpoolexecutor (1, 1, 0L, Timeunit.milliseconds, new linkedblockingqueue<runnable>())); }
Returns a thread pool of threads, executes if idle, and does not place the task in the queue waiting for
Executor.newcachedtreadpool
Public Static Executorservice Newcachedthreadpool () { returnnew threadpoolexecutor (0, Integer.max_value, 60L, timeunit.seconds, new synchronousqueue<runnable> ()); }
Returns a thread that adjusts the number of threads according to the actual situation the pond does not limit the maximum number of threads, if there are idle threads directly to the empty thread execution is not created, the thread is idle for more than 60 seconds to specify the recycle
Exucutor.newscheduledthreadpool
Public Static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize) { returnNew Scheduledthreadpoolexecutor (corepoolsize); }
Public Scheduledthreadpoolexecutor (int corepoolsize) { Super(Corepoolsize, Integer.max_value, 0, nanoseconds, new delayedworkqueue()); }
Public class Scheduledthreadpoolexecutor extends Threadpoolexecutor Implements Scheduledexecutorservice
You can discover or implement a queue using Threapoolexecutor with Deayedworkqueue
Returns the Schededexecutoryservice object
can implement scheduled tasks
public static void Main (string[] args) throws interruptedexception {scheduledexecutorservice Scheduledexecutorservice = Executors.newscheduledthreadpool ( 1); Scheduledexecutorservice.scheduleatfixedrate ( new Runnable () {@Override public void run () {System.out.println (" ); }}, 1,3,timeunit.seconds); // 1 for how long is the delay to execute 3 for rotation time timeunit.seconds for Time Unit }
Custom thread pool
The Threadpoolexecutor constructor
PublicThreadpoolexecutor (intCorepoolsize,//Number of core threads (number of default threads) intMaximumpoolsize,//Maximum number of threads (created if there are no idle threads exceeding the maximum number of threads) LongKeepAliveTime,//the life cycle of a threadTimeunit Unit,//KeepAliveTime Time UnitBlockingqueue<runnable> WorkQueue,//If no idle thread task is placed on the queuethreadfactory threadfactory, Rejectedexecutionhandler Handl ER)//The queue has a bounded queue. If the task queue is full. Custom actions for rejected tasks
Java thread pool