淺談Java 線程池原理及使用方式

一、簡介

  • 什麼是線程池?

池的概念大家也許都有所聽聞,池就是相當於一個容器,裏面有許許多多的東西你可以即拿即用。java中有線程池、連接池等等。線程池就是在系統啓動或者實例化池時創建一些空閒的線程,等待工作調度,執行完任務後,線程並不會立即被銷燬,而是重新處於空閒狀態,等待下一次調度。

  • 線程池的工作機制?

在線程池的編程模式中,任務提交併不是直接提交給線程,而是提交給池。線程池在拿到任務之後,就會尋找有沒有空閒的線程,有則分配給空閒線程執行,暫時沒有則會進入等待隊列,繼續等待空閒線程。如果超出最大接受的工作數量,則會觸發線程池的拒絕策略。

  • 爲什麼使用線程池?

線程的創建與銷燬需要消耗大量資源,重複的創建與銷燬明顯不必要。而且池的好處就是響應快,需要的時候自取,就不會存在等待創建的時間。線程池可以很好地管理系統內部的線程,如數量以及調度。

二、常用線程池介紹

Java類ExecutorService是線程池的父接口,並非頂層接口。以下四種常用線程池的類型都可以是ExecutorService。

  • 單一線程池 Executors.newSingleThreadExecutor()

內部只有唯一一個線程進行工作調度,可以保證任務的執行順序(FIFO,LIFO)

package com.test;

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

public class PoolTest {
	public static void main(String[] args) {
		// 創建單一線程池
		ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
		List<String> list = new ArrayList<String>();
		list.add("first");
		list.add("second");
		list.add("third");
		list.forEach(o -> {
			// 遍歷集合提交任務
			singleThreadExecutor.execute(new Runnable() {
				
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + " : " + o);
					try {
						// 間隔1s
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		});
	}
}

 執行結果:

pool-1-thread-1 : first

pool-1-thread-1 : second

pool-1-thread-1 : third

  • 可緩存線程池 Executors.newCachedThreadPool() 

如果線程池中有可使用的線程,則使用,如果沒有,則在池中新建一個線程,可緩存線程池中線程數量最大爲Integer.MAX_VALUE。通常用它來運行一些執行時間短,且經常用到的任務。

package com.test;

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

public class PoolTest {
	public static void main(String[] args) {
		// 創建可緩存線程池
		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		List<String> list = new ArrayList<String>();
		list.add("first");
		list.add("second");
		list.add("third");
		list.forEach(o -> {
			
			try {
				// 間隔3s
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			// 遍歷集合提交任務
			cachedThreadPool.execute(new Runnable() {
				
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + " : " + o);
					try {
						// 間隔1s
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		});
	}
}

執行結果:

pool-1-thread-1 : first

pool-1-thread-1 : second

pool-1-thread-1 : third

因爲間隔時間長,下一個任務運行時,上一個任務已經完成,所以線程可以繼續複用,如果間隔時間調短,那麼部分線程將會使用新線程來運行。

把每個任務等待時間從3s調低至1s:

執行結果:

pool-1-thread-1 : first

pool-1-thread-2 : second

pool-1-thread-1 : third
 

  • 定長線程池 Executors.newFixedThreadPool(int nThreads)

創建一個固定線程數量的線程池,參數手動傳入

package com.test;

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

public class PoolTest {
	public static void main(String[] args) {
		// 創建可緩存線程池
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
		List<String> list = new ArrayList<String>();
		list.add("first");
		list.add("second");
		list.add("third");
		list.add("fourth");
		list.forEach(o -> {
			
			try {
				// 間隔1s
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			// 遍歷集合提交任務
			fixedThreadPool.execute(new Runnable() {
				
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + " : " + o);
					try {
						// 間隔1s
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		});
	}
}

執行結果:

pool-1-thread-1 : first

pool-1-thread-2 : second

pool-1-thread-3 : third

pool-1-thread-1 : fourth 

  • 定時線程池 Executors.newScheduledThreadPool(int corePoolSize)

創建一個定長線程池,支持定時及週期性任務執行

package com.test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class PoolTest {
	public static void main(String[] args) {
		// 創建定長線程池、支持定時、延遲、週期性執行任務
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
		scheduledThreadPool.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + " : 1秒後每隔3秒執行一次");
			}
		}, 1, 3, TimeUnit.SECONDS);
	}
}

執行結果:

pool-1-thread-1 : 1秒後每隔3秒執行一次

pool-1-thread-1 : 1秒後每隔3秒執行一次

pool-1-thread-2 : 1秒後每隔3秒執行一次

pool-1-thread-2 : 1秒後每隔3秒執行一次

pool-1-thread-2 : 1秒後每隔3秒執行一次

pool-1-thread-2 : 1秒後每隔3秒執行一次

pool-1-thread-2 : 1秒後每隔3秒執行一次

三、自定義線程池

常用構造函數:

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

 參數說明:

1、corePoolSize 核心線程數大小,當線程數<corePoolSize ,會創建線程執行runnable

2、maximumPoolSize 最大線程數, 當線程數 >= corePoolSize的時候,會把runnable放入workQueue中

3、keepAliveTime  保持存活時間,當線程數大於corePoolSize的空閒線程能保持的最大時間。

4、unit 時間單位

5、workQueue 保存任務的阻塞隊列

6、threadFactory 創建線程的工廠

7、handler 拒絕策略

任務執行順序:

        1、當線程數小於corePoolSize時,創建線程執行任務。

        2、當線程數大於等於corePoolSize並且workQueue沒有滿時,放入workQueue中

        3、線程數大於等於corePoolSize並且當workQueue滿時,新任務新建線程運行,線程總數要小於maximumPoolSize

        4、當線程總數等於maximumPoolSize並且workQueue滿了的時候執行handler的rejectedExecution。也就是拒絕策略。

ThreadPoolExecutor默認有四個拒絕策略:

        1、new ThreadPoolExecutor.AbortPolicy()   直接拋出異常RejectedExecutionException

        2、new ThreadPoolExecutor.CallerRunsPolicy()    直接調用run方法並且阻塞執行

        3、new ThreadPoolExecutor.DiscardPolicy()   直接丟棄後來的任務

        4、new ThreadPoolExecutor.DiscardOldestPolicy()  丟棄在隊列中隊首的任務

緩衝隊列BlockingQueue:

  BlockingQueue是雙緩衝隊列。BlockingQueue內部使用兩條隊列,允許兩個線程同時向隊列一個存儲,一個取出操作。在保證併發安全的同時,提高了隊列的存取效率。

常用的幾種BlockingQueue:

  • ArrayBlockingQueue(int i):規定大小的BlockingQueue,其構造必須指定大小。其所含的對象是FIFO順序排序的。

  • LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue,若其構造時指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE來決定。其所含的對象是FIFO順序排序的。

  • PriorityBlockingQueue()或者(int i):類似於LinkedBlockingQueue,但是其所含對象的排序不是FIFO,而是依據對象的自然順序或者構造函數的Comparator決定。

  • SynchronizedQueue():特殊的BlockingQueue,對其的操作必須是放和取交替完成。

package com.test;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PoolTest {
	public static void main(String[] args) {
		// 工作隊列
		LinkedBlockingDeque<Runnable> workQueue = new LinkedBlockingDeque<Runnable>();
		// 拒絕策略
		RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10, 20, TimeUnit.MILLISECONDS, workQueue, handler);
		threadPoolExecutor.execute(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("自定義線程池");
			}
		});
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章