Java multi-thread (4) thread pool and java multi-thread pool
A good software does not randomly create and destroy threads, because it takes a lot of CPU time and requires a lot of interaction with the memory. Therefore, JDK 5 proposes to use the thread pool so that programmers can focus more on the business logic and weaken the thread open/closed management.
JDK provides four different thread pools for programmers to use.
First, the thread pool needs to be used. The ExecutorService interface has an abstract class called AbstractExecutorService to implement it. ThreadPoolExecutor further implements the abstract class. JDK encapsulates an Executor class to instantiate ThreadPoolExecutor. Therefore, Executor can be used to create a thread pool with the following four features:
1. No lower bound Thread Pool
ExecutorService threadPool = Executors. newCachedThreadPool (); when the number of threads is insufficient, the thread pool dynamically increases the number of threads for subsequent task scheduling.
2. fixed thread pool
ExecutorService threadPool = Executors. newFixedThreadPool (3); Create a thread pool with a fixed number of threads: 3
3. Single thread pool
ExecutorService threadPool = Executors. newSingleThreadScheduledExecutor (); create a single-instance thread pool to ensure that one thread is working at a constant time in the thread pool
4. Scheduling Thread Pool
ScheduledExecutorService threadPool = Executors. newSingleThreadScheduledExecutor (); creates a fixed-length thread pool to execute tasks regularly or cyclically
1 package com. scl. thread. threadPool; 2 3 import java. util. concurrent. executors; 4 import java. util. concurrent. scheduledExecutorService; 5 import java. util. concurrent. timeUnit; 6 7 public class ScheduledThreadPool 8 {9 public static void main (String [] args) 10 {11 // create a scheduled scheduling thread pool 12 ScheduledExecutorService threadPool = Executors. newSingleThreadScheduledExecutor (); 13 // scheduled Runnable14 threadPool. scheduleAtFixedRate (new Runnable () 15 {16 17 @ Override18 public void run () 19 {20 System. out. println ("do some big Scheduled"); 21} 22}, 10, 3, TimeUnit. SECONDS); 23} 24}Regular scheduling Thread Pool
It is also relatively simple to use the thread pool. You only need to submit a "task" to the thread pool. Generally, the object. submit method is used as follows:
① ThreadPool. submit (Callable <T> task );
Like the Runnable interface, Callable automatically calls the call method in the interface. Unlike the Runnable interface, the run method cannot return content. The call method contains return parameters. The Future interface can be used externally to receive the results returned by the thread. For example: Future <String> future = threadPool. submit (new MyTask ());
② ThreadPool. submit (Runnable task );
From this signature, we can also throw the Runnable interface instance to the thread pool.
As mentioned above, the use of the thread pool is to reduce the startup and shutdown of the thread by programmers. Create and close the thread to the thread pool. Therefore, the typical thread problem is to use the thread pool: producer-consumer model.
Model Introduction: This model is a typical queuing content. The model has three main roles: producer, consumer, and warehouse. The producer and consumer share the Warehouse Information. ① when the products in the warehouse are full, stop production and wait for the consumer to consume enough data before production. ② when the products in the warehouse are empty, wait for the producer to produce and then sell. ③ the Warehouse is responsible for carrying the product content.
An example of parking space management is provided based on the model content. There are three roles: CarOwner, Secure, and CarPark ). Different drivers drive the car into the garage, and the security guard is responsible for recording the number of vehicles leaving the garage. The garage capacity is fixed. If the garage is empty, a security guard can notify the owner to drive the car into the garage. If the garage is full, the security guard tells the car owner to wait for another car owner to drive the car out. The garage uses a list to record the information of the vehicles in the warehouse.
Therefore, there are the following class diagrams:
1 package com. scl. thread. threadPool. carParkManager; 2 3 public class CarOwner implements Runnable 4 {5 private int driverInNum; 6 private CarPark carPark; 7 8 public CarOwner (CarPark carPark) 9 {10 this. carPark = carPark; 11} 12 13 @ Override14 public void run () 15 {16 carPark. driverIn (driverInNum); 17} 18 19 public int getDriverInNum () 20 {21 return driverInNum; 22} 23 24 public void setDriverInNum (int driverInNum) 25 {26 this. driverInNum = driverInNum; 27} 28}Car holder CarOwner parking lot CarPark 1 package com. scl. thread. threadPool. carParkManager; 2 3 public class Car 4 {5 private String id; 6 private String name; 7 8 public Car (String id, String name) 9 {10 this. id = id; 11 this. name = name; 12} 13 14}Car 1 package com. scl. thread. threadPool. carParkManager; 2 3 public class Secure implements Runnable 4 {5 private int driverOutNum; 6 7 private CarPark carPark; 8 9 public Secure (CarPark carPark) 10 {11 this. carPark = carPark; 12} 13 14 public int getDriverOutNum () 15 {16 return driverOutNum; 17} 18 19 public void setDriverOutNum (int driverOutNum) 20 {21 this. driverOutNum = driverOutNum; 22} 23 24 @ Override25 public void run () 26 {27 carPark. driverOut (driverOutNum); 28} 29}Security guard Secute 1 package com. scl. thread. threadPool. carParkManager; 2 3 import java. util. concurrent. executorService; 4 import java. util. concurrent. executors; 5 6 public class Client 7 {8 9 public static void main (String [] args) 10 {11 // set the maximum garage value 12 CarPark carPark = new CarPark (5 ); 13 // create thread pool 14 ExecutorService threadPool = Executors. newCachedThreadPool (); 15 // create three car owners 16 CarOwner cw1 = new CarOwner (carPark); 17 CarOwner cw2 = new CarOwner (carPark ); 18 CarOwner cw3 = new CarOwner (carPark); 19 // set the number of vehicles to enter 20 cw1.setDriverInNum (3); 21 cw2.setDriverInNum (3); 22 cw3.setDriverInNum (1 ); 23 24 // create three security guards 25 Secure s1 = new Secure (carPark); 26 Secure s2 = new Secure (carPark); 27 Secure s3 = new Secure (carPark ); 28 s1.setDriverOutNum (1); 29 s2.setDriverOutNum (2); 30 s3.setDriverOutNum (1); 31 32 threadPool. submit (cw1); 33 threadPool. submit (cw2); 34 threadPool. submit (cw3); 35 threadPool. submit (s1); 36 threadPool. submit (s2); 37 threadPool. submit (s3); 38 39} 40 41}Client
The code above shows that there is no big difference between submitting using a Thread pool and using a Thread class. JDK5 provides a blocking queue that can better simulate the producer-consumer model. We will make a summary later.
The above is the summary of the thread pool. If there is any error or omission, please point it out and correct it.