Multi-thread programming (5) -- thread pool, multi-thread programming -- Thread Pool
The Java. util. concurrent package is added after JDK 1.5. This package mainly introduces the use of threads and thread pools in java. It provides great help for us to handle thread issues during development.
I. Origin of the pool
Take the database as an example: a new link is created whenever a request arrives, but when there are a large number of concurrent requests for access, the link will be continuously created and destroyed, with high overhead. In order to improve efficiency and achieve the effect of reuse, we have the concept of a pool.
A thread pool is a technology used to create threads in advance. The thread pool creates a certain number of threads before the task arrives and puts them in the idle queue. These threads are all in sleep state, that is, they are all started, not consuming CPU, but occupying a small amount of memory space. When the request arrives, the buffer pool allocates an idle thread to the request and passes the request to the thread for processing. When all the pre-created threads are in the running state, that is, the pre-created threads are insufficient, the thread pool can freely create a certain number of new threads to process more requests. When the system is idle, you can also remove some threads that have been in the stopped status.
Ii. advantages of using a thread pool
1. reduces the number of threads created and destroyed to maximize the number of reusable objects
2. Separation of thread code and Business Code
Iii. thread pool usage
The top-level interface of the thread pool in Java is Executor, but in a strict sense, Executor is not a thread pool, but a tool for executing the thread. The real thread pool interface is ExecutorService.
1. fixed thread pool
ExecutorServicethreadPool = Executors. newFixedThreadPool (3); // create a thread pool that can accommodate three threads
2. cache Thread Pool
ExecutorServicethreadPool = Executors. newCachedThreadPool (); // The thread pool size is dynamically allocated based on the number of executed tasks.
3. Single thread pool
ExecutorServicethreadPool = Executors. newSingleThreadExecutor (); // there is only one thread in the pool. The advantage is that if the thread in the pool dies, it will start another thread, so after the thread is restarted
Code:
Public static voidmain (String [] args) {// fixed thread pool ExecutorServicethreadPool = Executors. newFixedThreadPool (3); // cache thread pool // ExecutorServicethreadPool = Executors. newCachedThreadPool (); // there is only one thread in the pool. The advantage is that if the thread in the pool is dead, it will start another thread, so it will restart a thread after the thread is dead. // ExecutorServicethreadPool = Executors. newSingleThreadExecutor (); for (int I = 1; I <= 10; I ++) {finalint task = imo-threadpool.exe cute (newRunnable () {@ Overridepublicvoid Run () {for (int j = 1; j <10; j ++) {try {Thread. sleep (20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "is looping of" + j + "for task of" + task) ;}});} System. out. println ("allof 10 task have committed! "); // After 6 s, blow Executors every 2 s. newScheduledThreadPool (3 ). scheduleAtFixedRate (newRunnable () {@ Overridepublicvoid run () {System. out. println ("bombing") ;},6, 2, TimeUnit. SECONDS); // blow up after 6 s, blow up every 2 s }}
Running effect:
Fixed thread:
Three threads are currently set, so these three threads are working. There is a fixed size pool in FixedThreadPool. If the current task to be executed exceeds the pool size, the redundant task waits until there are Idle threads to execute the task, when the executed task is smaller than the pool size, Idle threads will not be destroyed. If a thread ends due to an execution exception, the thread pool adds a new thread.
Cache thread:
These threads work alternately. CachedThreadPool will create a cache zone and cache the initialization thread. If the thread pool size exceeds the thread required for processing the task, then, some Idle threads (which do not execute tasks in 60 seconds) will be reclaimed. When the number of tasks increases, the thread pool can intelligently add new threads to process the tasks. This thread pool does not limit the thread pool size. The thread pool size depends entirely on the maximum thread size that can be created by the operating system (or JVM.
Single thread pool
Only one thread is working. This thread pool ensures that all tasks are executed in the order they are submitted.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.