Java multithreading Series 4-thread pool, java multithreading 4-Thread
In the previous article, I learned how to implement java. lang. Runnable to define classes and create a thread to run tasks as follows:
Runnable task = new TaskClass (task );
New Thread (task). start ();
This method is convenient for a single task, but not efficient for a large number of tasks. Starting a new thread for each task may limit traffic and cause performance degradation.
Java provides the Executor interface to execute tasks in the thread pool and the ExecutorService interface to manage and control tasks. The ExecutorService interface is a subinterface of the Executor interface.
NewFixedThreadPool
Public static ExecutorServiceNewFixedThreadPool(Int nThreads)
Create a thread pool that can reuse a fixed number of threads and run these threads in a shared, unbounded queue mode. In any sense, in mostNThreadsThe thread is in the active state of the processing task. If an additional task is submitted when all threads are active, the additional task will wait in the queue before there is an available thread. If any thread is terminated due to a failure during the execution before it is disabled, a new thread will execute subsequent tasks (if needed) in place of it ). ExplicitlyClosePreviously, the thread in the pool will always exist.
Parameters:nThreads-Number of threads in the pool
Return Value:Newly created thread pool
Throw:IllegalArgumentException-IfNThreads <= 0
NewCachedThreadPool
Public static ExecutorServiceNewCachedThreadPool()
Create a thread pool where new threads can be created as needed, but they will be reused when previously constructed threads are available. For programs that execute many short-term asynchronous tasks, these thread pools can usually improve program performance. CallExecuteThe previously constructed thread will be reused (if the thread is available ). If the existing thread is not available, create a new thread and add it to the pool. Terminate and Remove unused threads from the cache for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources. Note: You can useThreadPoolExecutorConstructor creates a thread pool with similar properties but different details (such as timeout parameters.
Return Value:Newly created thread pool
Let's look at a multi-threaded example:
Package ExecuterTest; public class TaskThreadDemo {public static void main (String [] args) {// create a task and Thread th1 = new Thread (new PrintChar ('A ', 100); Thread Th1 = new Thread (new PrintChar ('B', 100); Thread th3 = new Thread (new PrintNum (100 )); // start thread th1.start (); th2.start (); th3.start () ;}// the task is to print the specified number of times of the specified character class PrintNum implements Runnable {private int lastNum; public PrintNum (int n) {lastNum = n ;}@ Override public void run () {for (int I = 1; I <= lastNum; I ++) {System. out. println ("" + I) ;}}// the task is to print all the numbers from 1 to n. class PrintChar implements Runnable {private char charToPrint; // print the character private int times; // print times public PrintChar (char c, int t) {charToPrint = c; times = t ;}@ Override public void run () {for (int I = 0; I <times; I ++) {System. out. println (charToPrint );}}}
The thread pool is used to modify the above program:
Import java. util. concurrent. executorService; import java. util. concurrent. executors; public class TaskThreadDemo {public static void main (String [] args) {// create a thread pool where the maximum number of threads is 3 ExecutorService excutor = Executors. newFixedThreadPool (3); // submit the runnable () task to excutor excutor.exe cute (new PrintChar ('A', 100); excutor.exe cute (new PrintChar ('B ', 100); excutor.exe cute (new PrintNum (100); // disable excutor. shutdown ();}}
If you change row 6th:
ExecutorService excutor = Executors. newFixedThreadPool (1 );
There is only one thread in the thread pool, and the three threads are executed sequentially.
If you change row 6th:
ExecutorService excutor = Executors. newCachedThreadPool ();
All threads are executed concurrently.