Java Multithreading - New Features - Thread Pool

In Java5, Sun has done a lot of expansion to the class library of Java threads, among which the thread pool is one of the new features of Java5. In addition to the thread pool, there are many multi-threading related content, which brings multi-threaded programming. Great convenience. In order to write efficient, stable and reliable multi-threaded programs, the new content of the thread section is particularly important.

The content about the new features of Java5 threads is all under java.util.concurrent, which contains a large number of interfaces and classes. It is a difficult learning process to be familiar with this part of the API features. At present, there are very few materials and books on this aspect, and most of the books that introduce threads are still at the knowledge level before java5.

Before Java5, it was quite difficult to implement a thread pool. Now Java5 has done everything for us. We only need to use the provided API to enjoy the great convenience brought by the thread pool.

The basic idea of ​​the thread pool is still the idea of ​​an object pool, which opens up a memory space in which many (not dead) threads are stored. The thread execution scheduling in the pool is handled by the pool manager. When there is a thread task, one is taken from the pool, and the thread object is returned to the pool after the execution is completed, which can avoid the performance overhead caused by repeatedly creating thread objects and save system resources.

Java5 provides 5 types of thread pools, as follows:

One: newCachedThreadPool - variable size thread pool (cached thread pool) 
(1) Cached pool, first check if there are any previously created threads in the pool, if so, reuse (reuse), if not, create a new one Threads are added to the pool; 
(2) Cached pools are usually used to execute some asynchronous tasks with a short life cycle ; therefore, some connection-oriented daemon servers are not used much; 
(3) Threads that can be reused , must be a thread in the pool in the timeout IDLE, the default timeout is 60s, if the IDLE duration is exceeded, the thread instance will be terminated and removed from the pool; 
(4) Note that the thread placed in the CachedThreadPool does not have to worry about its end, it will not be active after TIMEOUT , it is automatically terminated.

Two: newFixedThreadPool-fixed-size thread pool 
(1) newFixedThreadPool is similar to cacheThreadPool, it can also be reused, but cannot create new threads at any time; 
(2) Its uniqueness: at any point in time, there can only be a fixed number of activities at most The thread exists. If there is a new thread to be established at this time, it can only wait in another queue until a thread in the current thread terminates and is directly removed from the pool; 
(3) Unlike cacheThreadPool, FixedThreadPool does not have an IDLE mechanism (possibly There are also, but since the document does not mention it, it must be very long, similar to relying on the upper-layer TCP or UDP IDLE mechanism, etc.), so FixedThreadPool mostly targets some very stable and fixed regular concurrent threads, and is mostly used for servers
(4) From the method From the source code, the cache pool and the fixed pool call the same underlying pool, but with different parameters: the
fixed pool has a fixed number of threads, and it is 0 seconds IDLE (no IDLE); the
cache pool thread number supports 0-Integer.MAX_VALUE (obviously It does not take into account the resource affordability of the host at all), 60 seconds of IDLE.

Three: ScheduledThreadPool-Scheduled Thread Pool 
(1) Scheduled thread pool; 
(2) Threads in this pool can be executed sequentially according to schedule , or executed periodically.

Four: SingleThreadExecutor-Singleton thread pool 
(1) Singleton thread, there can only be one thread in the pool at any time
(2) It uses the same underlying pool as the cache pool and the fixed pool, but the number of threads is 1-1, 0 seconds IDLE (no IDLE).

copy code
package cn.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池用法
 * 
 * @author 林计钦
 * @version 1.0 2013-7-25 上午10:00:46
 */
public class ThreadPoolTest {
    public static void main(String[] args) {
        ThreadPoolTest test=new ThreadPoolTest();
        
        //创建一个可重用固定线程数的线程池 
        ExecutorService pool = Executors.newFixedThreadPool(2); 
        //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口 
        Thread t1 = test.new MyThread(); 
        Thread t2 = test.new MyThread(); 
        Thread t3 = test.new MyThread(); 
        Thread t4 = test.new MyThread(); 
        Thread t5 = test.new MyThread(); 
        //将线程放入池中进行执行 
        pool.execute(t1); 
        pool.execute(t2); 
        pool.execute(t3); 
        pool.execute(t4); 
        pool.execute(t5); 
        //关闭线程池 
        pool.shutdown(); 
    }
    
    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "正在执行。");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
copy code

五、自定义线程池--ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)

参数:
corePoolSize 
核心线程数,核心线程会一直存活,即使没有任务需要处理。当线程数小于核心线程数时,即使现有的线程空闲,线程池也会优先创建新线程来处理任务,而不是直接交给现有的线程处理。
核心线程在allowCoreThreadTimeout被设置为true时会超时退出,默认情况下不会退出。

maximumPoolSize
当线程数大于或等于核心线程,且任务队列已满时,线程池会创建新的线程,直到线程数量达到maxPoolSize。如果线程数已等于maxPoolSize,且任务队列已满,则已超出线程池的处理能力,线程池会拒绝处理任务而抛出异常。

keepAliveTime 
当线程空闲时间达到keepAliveTime,该线程会退出,直到线程数量等于corePoolSize。如果allowCoreThreadTimeout设置为true,则所有线程均会退出直到线程数量为0。

unit 
keepAliveTime 参数的时间单位。

workQueue 
执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务。

抛出:
IllegalArgumentException - 如果corePoolSize或keepAliveTime小于零,或者maximumPoolSize小于或等于零,或者corePoolSize 大于maximumPoolSize。
NullPointerException - 如果workQueue为null

eg、
//创建等待队列 
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(20); 
//创建一个单线程执行程序,它可安排在给定延迟后运行命令或者定期地执行。 
ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 3, 2, TimeUnit.MILLISECONDS, queue); 
//创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口 
Thread t1 = new MyThread(); 
Thread t2 = new MyThread(); 
//将线程放入池中进行执行 
pool.execute(t1); 
pool.execute(t2); 
//关闭线程池 
pool.shutdown();

copy code
package cn.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义连接池
 * 
 * @author 林计钦
 * @version 1.0 2013-7-25 上午10:09:17
 */
public class ThreadPoolExecutorTest {

    public static void main(String[] args) {
        ThreadPoolTest test = new ThreadPoolTest();

        // 创建等待队列
        BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20);
        // 创建一个单线程执行程序,它可安排在给定延迟后运行命令或者定期地执行。
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 3, 2, TimeUnit.MILLISECONDS, bqueue);
        // 创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口
        Thread t1 = test.new MyThread();
        Thread t2 = test.new MyThread();
        Thread t3 = test.new MyThread();
        Thread t4 = test.new MyThread();
        Thread t5 = test.new MyThread();
        Thread t6 = test.new MyThread();
        Thread t7 = test.new MyThread();
        // 将线程放入池中进行执行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.execute(t6);
        pool.execute(t7);
        // 关闭线程池
        pool.shutdown();
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "Executing." );
             try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        }
    }

}
copy code

Reference: Analysis and use of thread pools

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326233824&siteId=291194637