自己動手實現簡單的線程池,自己動手線程池
為了節省系統在多線程並發情況下不斷的建立新和銷毀線程所帶來的效能浪費,就需要引入線程池。
線程池的準系統就是線程複用。每當系統提交一個任務時,會嘗試從線程池內取出空閑線程來執行它。如果沒有空閑線程,這時候再建立新的線程。任務執行完畢,線程也不會立即銷毀,而是加入到線程池中以便下次複用。
Java提供了多種線程池的實現,以滿足不同業務的需求。為了理解它們,下面給出一個最簡單的線程池的實現。
線程池主要分為兩大部分,線程池和一些永不退出的線程
首先是線程池部分:
package optimistic;import java.util.List;import java.util.Vector;public class ThreadPool {//使用單例模式建立線程池private static ThreadPool pool;private final List<PThread> threads;private volatile boolean isShutdown;private int threadCount = 0;// 線上程中調用,用來將自己加入線程池中synchronized public void putThread(PThread t) {if (!isShutdown) {threads.add(t);} else {t.shutdown();}}// 用戶端用來執行自己的一項任務synchronized public void start(Runnable task) {if (!isShutdown) {if (threads.size() < 1) {new PThread(task, pool).start();} else {PThread p = threads.remove(0);//設定好p.setTarget(task);}}}//初始化一個大小為5的線程池數組synchronized public static ThreadPool getThreadPool() {if (pool == null) {pool = new ThreadPool(5);}return pool;}public ThreadPool(int poolSize) {threads = new Vector<PThread>(poolSize);isShutdown = false;}//如果關閉線程池,需要將所有線程也關閉synchronized public void shutdown() {for(PThread p : threads)p.shutdown();threads.clear();isShutdown = true;}public int getThreadCount(){return threads.size();}}
其次,我們還需要一個永不退出的線程與之配合。
package optimistic;public class PThread extends Thread {private final ThreadPool pool;private volatile boolean isShutdown;private Runnable target;public PThread(Runnable task, ThreadPool pool) {this.target = task;this.pool = pool;isShutdown = false;}@Overridepublic void run() {while (!isShutdown) {if (target != null) {target.run();}try {pool.putThread(this);// 線程執行完任務,會在wait處阻塞,直到 setTarget或者 shutdown 調用notifyAllsynchronized (this) {wait();}} catch (InterruptedException e) {}}}// 每當設定任務或關閉時會喚醒run方法synchronized public void setTarget(Runnable r) {this.target = r;notifyAll();}synchronized public void shutdown() {isShutdown = true;notifyAll();}}
完成這主要的兩部分之後,我們就只需要定義一個Runnable和一個主線程就好了。
package optimistic;public class Controller {public static void main(String[] args) throws InterruptedException {ThreadPool pool = ThreadPool.getThreadPool();Runnable r = new Runnable() {public void run() {System.out.println(Thread.currentThread().getName());try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}};for (int i = 0; i < 10; i++)pool.start(r);Thread.sleep(1500);System.out.println(pool.getThreadCount());pool.shutdown();Thread.sleep(1000);System.out.println(pool.getThreadCount());}}