Java provides four thread pools through executors, namely:
Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.
Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.
Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).
Read more about blog Java Concurrent Programming: using the thread pool
1.newCachedThreadPool the thread pool here is infinitely large, and when a thread finishes the task, it can then complete the task that will be assigned instead of creating a new thread.
Public Static voidMain (string[] args) {Executorservice Cachedthreadpool=Executors.newcachedthreadpool (); for(inti = 0; I < 10; i++) { Final intindex =i; Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } cachedthreadpool.execute (NewRunnable () { Public voidrun () {System.out.println (index); } }); } }
2.newFixedThreadPool
Public Static voidMain (string[] args) {Executorservice Fixedthreadpool= Executors.newfixedthreadpool (3); for(inti = 0; I < 10; i++) { Final intindex =i; Fixedthreadpool.execute (NewRunnable () { Public voidrun () {Try{System.out.println (index); Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } } }); } }
3.newScheduledThreadPoo
public static void main (string[] args) {scheduledexecutorservice Scheduledthreadpool = Executo Rs.newscheduledthreadpool (5 for (int i = 0; i <; I++ new Runnable () { public void run () {System.out.println (" Delay 3 seconds "); }}, 3
4.newSingleThreadExecutor executes thread tasks sequentially but unlike single threads, the thread pool can only have one thread, which is routines by the other line after death.
Public Static voidMain (string[] args) {Executorservice singlethreadexecutor=Executors.newsinglethreadexecutor (); for(inti = 0; I < 10; i++) { Final intindex =i; Singlethreadexecutor.execute (NewRunnable () { Public voidrun () {/*System.out.println (index);*/ Try{System.out.println (index); Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } } }); } }
Four ways to create a Java thread pool