本篇主要用作鏈接使用。
線程池的核心就是,當接收到一個任務,需要一個線程去執行時,并不著急創建一個線程,而是先去線程池檢查是否有空閑的線程,如果有,則直接使用,如果沒有則創建新的線程,然后執行任務。任務執行完成后,也不著急銷毀線程,而是將線程放到線程池的空閑隊列中,等待下次使用。
首先是線程池的實現。
首先是線程池的實現:
/**
* Created by Joker on 2015/3/7.
*/
public class ThreadPool {
private static ThreadPool instance = null;
//空閑的線程隊列
private List<JThread> idleThreads;
//已有的線程總數
private int threadCounter = 0;
private Boolean isShunDown = false;
public ThreadPool() {
//初始化空閑線程隊列容量為5
this.idleThreads = new Vector<JThread>(5);
this.threadCounter = 0;
}
private static class SingleTonHolder {
private static ThreadPool threadPool = new ThreadPool();
}
/*單例獲得線程池實例*/
public static ThreadPool getInstance() {
return SingleTonHolder.threadPool;
}
public int getThreadCounter() {
return threadCounter;
}
/**
* 將線程放入池中,回收線程
*/
protected synchronized void repool(JThread repoolingThread) {
if (!isShunDown) {
idleThreads.add(repoolingThread);
} else {
repoolingThread.shutDown();
}
}
/**
* 停止池中所有線程
*/
public synchronized void shutDownAll() {
this.isShunDown = true;
for (JThread jThread : idleThreads) {
jThread.shutDown();
}
}
/**
* 執行線程任務
*/
public synchronized void execute(Runnable target) {
this.isShunDown = false;
JThread jThread = null;
/*如果池中有空余線程,直接使用該線程*/
if (idleThreads.size() > 0) {
jThread = idleThreads.get(idleThreads.size() - 1);
//將該線程從池中移除
idleThreads.remove(jThread);
//立即執行該任務
jThread.setTarget(target);
}
/*沒有空閑線程,創建新線程*/
else {
threadCounter++;
//創建線程
jThread = new JThread(target, "JThread:" + threadCounter, ThreadPool.this);
jThread.start();
}
}
}
要使用上述線程池,還需要一個永不退出的工作現場與之配合。是一個While
循環,手動關閉之前,永不結束,一直等待新的任務進來。
該工作線程的實現如下:
/**
* Created by Joker on 2015/3/7.
*/
public class JThread extends Thread {
//線程池
private ThreadPool threadPool;
//任務
private Runnable target;
private boolean isShutDown = false;
private boolean isIdle = false;
public JThread(Runnable target, String name, ThreadPool threadPool) {
super(name);
this.target = target;
this.threadPool = threadPool;
}
public Runnable getTarget() {
return target;
}
public boolean isIdle() {
return isIdle;
}
@Override
public void run() {
//只要沒有關閉,則一直不結束該線程
while (!isShutDown) {
isIdle = false;
if (null != target) {
//執行任務,注意這里調用的是run(),而不是start()
target.run();
}
//任務結束,閑置狀態
isIdle = true;
try {
threadPool.repool(JThread.this);
synchronized (this) {
//線程空閑,等待新的任務到來
wait();
}
} catch (InterruptedException e) {
}
isIdle = false;
}
}
public synchronized void setTarget(Runnable target) {
this.isShutDown = false;
this.target = target;
//設置任務之后,通知run方法,開始執行任務
notifyAll();
}
/**
* 關閉線程
*/
public synchronized void shutDown() {
this.isShutDown = true;
notifyAll();
}
}
使用方法如下:
ThreadPool.getInstance().execute(new Runnable() {
@Override
public void run() {
/*執行任務*/
}
});