java多線程——線程池

爲何要使用線程池?java

(1)下降資源消耗。經過重複利用已建立的線程下降線程建立和銷燬形成的消耗。緩存

(2)提升響應速度。當任務到達時,任務能夠不須要等到線程建立就能當即執行。ide

(3)提升線程的可管理性。線程是稀缺資源,若是無限制的建立,不只會消耗系統資源,還會下降系統的穩定性,使用線程池能夠進行統一的分配,調優和監控。this

建立和使用線程池:
線程

在java中咱們可使用new ThreadPoolExecutor(...) 來建立線程池code

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
    
corePoolSize - 池中所保存的線程數,包括空閒線程。
maximumPoolSize - 池中容許的最大線程數。
keepAliveTime - 當線程數大於核心時,此爲終止前多餘的空閒線程等待新任務的最長時間。
unit - keepAliveTime 參數的時間單位。
workQueue - 執行前用於保持任務的隊列。此隊列僅保持由 execute 方法提交的 Runnable 任務。

通常狀況下咱們不用自定義線程池,java中提供了大量建立鏈接池的靜態方法,接下來咱們來介紹經常使用的幾種:隊列

首先看一下線程池的類圖結構:資源

(1)固定大小的線程池 get

ExecutorService pool = Executors.newFixedThreadPool(10)it

(2)單線程化的線程池

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor()

(3)可緩存線程池

ExecutorService cachedThreadPool = Executors.newCachedThreadPool

(4)一個定長線程池,支持定時及週期性任務執行

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

簡單實用線程池例子:

public class ThreadPoolTest {
    public static void main(String[] args) {
        
        // 固定大小線程池
        ExecutorService pool = Executors.newFixedThreadPool(2);
        //建立5個線程
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = 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() + "正在執行。。。");
    }
}

//執行結果
pool-1-thread-1正在執行。。。
pool-1-thread-2正在執行。。。
pool-1-thread-1正在執行。。。
pool-1-thread-2正在執行。。。
pool-1-thread-1正在執行。。。