A good software does not arbitrarily create and destroy threads, because creating and destroying threads takes a lot of CPU time and requires a lot of interaction with memory. So JDK5 put forward the use of thread pool, let the programmer put more effort on the business logic above, weaken the open and close management of the thread.
The JDK provides four different thread pools for programmers to use
First, using the thread pool, the Executorservice interface needs to be used, the interface has an abstract class abstractexecutorservice to implement it, threadpoolexecutor further the implementation of the abstract class. Finally, the JDK encapsulates a executor class to instantiate the Threadpoolexecutor, so executor can create a thread pool with the following four attributes
1. No lower boundary pool
Executorservice threadpool= Executors.newcachedthreadpool (); When the number of threads is insufficient, the thread pool dynamically increases the threads for subsequent task scheduling
2. Thread pool with fixed number of threads
executorservice threadpool= executors.newfixedthreadpool (3); Create a thread pool with a fixed number of threads: 3
3. Single Thread thread pool
Executorservice threadpool= executors.newsinglethreadscheduledexecutor (); Create a singleton thread pool to ensure that there are 1 threads at work
4. Scheduling thread pool
Scheduledexecutorservice threadpool= executors.newsinglethreadscheduledexecutor (); Create a fixed-line pool to perform tasks on a regular or periodic basis
1 PackageCom.scl.thread.threadPool;2 3 Importjava.util.concurrent.Executors;4 ImportJava.util.concurrent.ScheduledExecutorService;5 ImportJava.util.concurrent.TimeUnit;6 7 Public classScheduledthreadpool8 {9 Public Static voidMain (string[] args)Ten { One //Create a timed dispatch thread pool AScheduledexecutorservice ThreadPool =executors.newsinglethreadscheduledexecutor (); - //timed Execution runnable -Threadpool.scheduleatfixedrate (NewRunnable () the { - - @Override - Public voidRun () + { -System.out.println ("Do some big scheduled"); + } A}, 10, 3, timeunit.seconds); at } -}timed scheduling thread pool
Using the thread pool is also relatively straightforward, as long as you submit a "task" to the thread pool, you will typically use the object. Submit method, as follows:
①threadpool.submit (Callable<t>task);
callable, like the Runnable interface, automatically calls the call method inside when the interface is used. Unlike the Runnable interface, where the Run method cannot return content, the call method contains a return parameter that can be accepted externally by the future interface to accept the results returned by the thread. such as:future<string> future = Threadpool.submit (New MyTask ());
②threadpool.submit (Runnable task);
as you can see from this signature, you can also throw a runnable interface instance into the thread pool.
As mentioned above, the thread pool is used to reduce the programmer's startup and shutdown of threads. The threads are created and closed to the thread pool to complete. So use the thread pool to complete the classic threading problem: producer-consumer models.
Introduction to the Model: the model is a typical queued content. The model is divided into three main roles: producers, consumers, warehouses. Producers and consumers to share warehouse information, ① when the warehouse inside the product is full, stop production waiting for consumers to spend enough to produce ② when the product in the warehouse is empty, waiting for the producer to produce and then sell ③ warehouse responsible for carrying the product content
According to the model content, a parking space management example was made. It is divided into three roles: vehicle holder (Carowner), security (secure), Garage (CarPark). Different car holders drive into the garage, and the security guards record the number of vehicles leaving the garage. Garage capacity is fixed, if the garage is empty security can inform the car owner to drive into the garage. If the garage is full, the security guard informs the owner to wait for another owner to drive the car out. Garage use a list to record the information of the vehicles in the warehouse.
So there are the following class diagrams:
1 PackageCom.scl.thread.threadPool.CarParkManager;2 3 Public classCarownerImplementsRunnable4 {5 Private intDriverinnum;6 PrivateCarPark CarPark;7 8 PublicCarowner (CarPark CarPark)9 {Ten This. CarPark =CarPark; One } A - @Override - Public voidRun () the { - Carpark.driverin (driverinnum); - } - + Public intGetdriverinnum () - { + returnDriverinnum; A } at - Public voidSetdriverinnum (intdriverinnum) - { - This. Driverinnum =Driverinnum; - } -}Car holder CarownerParking CarPark
1 PackageCom.scl.thread.threadPool.CarParkManager;2 3 Public classCar4 {5 PrivateString ID;6 PrivateString name;7 8 PublicCar (string ID, string name)9 {Ten This. ID =ID; One This. Name =name; A } - -}car information class car
1 PackageCom.scl.thread.threadPool.CarParkManager;2 3 Public classSecureImplementsRunnable4 {5 Private intDriveroutnum;6 7 PrivateCarPark CarPark;8 9 PublicSecure (CarPark CarPark)Ten { One This. CarPark =CarPark; A } - - Public intGetdriveroutnum () the { - returnDriveroutnum; - } - + Public voidSetdriveroutnum (intdriveroutnum) - { + This. Driveroutnum =Driveroutnum; A } at - @Override - Public voidRun () - { - carpark.driverout (driveroutnum); - } in}Security Secute
1 PackageCom.scl.thread.threadPool.CarParkManager;2 3 ImportJava.util.concurrent.ExecutorService;4 Importjava.util.concurrent.Executors;5 6 Public classClient7 {8 9 Public Static voidMain (string[] args)Ten { One //Setting the maximum garage value ACarPark CarPark =NewCarPark (5); - //Create a thread pool -Executorservice ThreadPool =Executors.newcachedthreadpool (); the //creation of three vehicle holders -Carowner CW1 =NewCarowner (CarPark); -Carowner CW2 =NewCarowner (CarPark); -Carowner CW3 =NewCarowner (CarPark); + //set the number of vehicles that need to drive in -Cw1.setdriverinnum (3); +Cw2.setdriverinnum (3); ACw3.setdriverinnum (1); at - //creation of three security guards -Secure S1 =NewSecure (CarPark); -Secure s2 =NewSecure (CarPark); -Secure s3 =NewSecure (CarPark); -S1.setdriveroutnum (1); inS2.setdriveroutnum (2); -S3.setdriveroutnum (1); to + Threadpool.submit (CW1); - Threadpool.submit (CW2); the Threadpool.submit (CW3); * Threadpool.submit (S1); $ threadpool.submit (S2);Panax Notoginseng Threadpool.submit (S3); - the } + A}Client Clients
As the code above shows, there is not much difference between using the thread pool and using the thread class to commit. JDK5 provides a blocking queue that is better able to simulate a producer-consumer model. Follow up and then summarize.
The above is the thread pool summary content, if there are mistakes please point out correction.
Java multithreaded (quad) thread pool