最近为了加强对线程池的理解,写了一个简单的线程池,实现思路是实现ThreadManager类,他拥有一个任务队列LinkedBlockingDeque<Runnable> tasks、空闲的worker集合free、工作中的worker集合working以及一个调度线程 dispacher ;工作方式是通过ThreadManager.execute方法将任务加入到tasks队列,然后由dispacher线程消费任务,从free获取空闲的worker,然后交给worker执行并将该worker放入working集合,等到worker执行任务完成后,再调用ThreadManager.addFree方法,进入空闲集合。ThreadManager.java代码如下:
package org.cylx.ml.core.thread;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
/**
*
* @author root
*
*/
public class ThreadManager {
private LinkedBlockingDeque<Runnable> tasks = new LinkedBlockingDeque<Runnable>();
private ConcurrentHashMap<Long, Worker> free = new ConcurrentHashMap<Long, Worker>();
private ConcurrentHashMap<Long, Worker> working = new ConcurrentHashMap<Long, Worker>();
private boolean close = false;
private Object isWait = new Object();// 是否等待
private int size;
public void execute(Runnable task) {
tasks.add(task);
synchronized (isWait) {
this.isWait.notifyAll();
}
}
public void close() {
this.close = true;
while (true) {
int size = working.size() + free.size();
if (size == this.size) {
break;
} else {
try {
Thread.sleep(200);
} catch (Exception ex) {
}
}
}
Set<Entry<Long, Worker>> set = free.entrySet();
set.addAll(working.entrySet());
for (Entry<Long, Worker> wk : set) {
wk.getValue().close();
}
synchronized (isWait) {
isWait.notifyAll();
}
}
public ThreadManager(int size) {
if (size < 1) {
//
throw new RuntimeException("非法参数");
}
this.size = size;
this.dispacher.start();// 启动管理线程
for (int i = 0; i < size; i++) {
new Worker(this);// 实例化工作线程
}
}
private Thread dispacher = new Thread() {
public void run() {
while (!close) {
Runnable task = tasks.peek();
if (task == null) {// 无任务
synchronized (isWait) {
try {
isWait.wait();
if (close) {
break;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (task != null) {
boolean f = exe(task);// 只有dispacher线程访问该方法
if (!f) {// 资源不足
synchronized (isWait) {
try {
isWait.wait();
if (close) {
tasks.clear();// 清空任务结束
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
tasks.poll();// 出队列
}
}
}
System.out.println("调度线程结束!");
//
}
};
private boolean exe(Runnable task) {
// 存在锁,当worker工作结束申请加入free和dispacher调度task,存在共享
if (this.free.isEmpty()) {
return false;
}
if (this.free.keys().hasMoreElements()) {
Long key = this.free.keys().nextElement();
Worker worker = this.free.get(key);// 得到一个空闲的线程
this.free.remove(key);
if (worker != null) {
this.working.put(worker.getId(), worker);// 加入工作中集合
boolean flag = worker.handler(task);
if (!flag) {
throw new RuntimeException("运行状态错误");
}
return flag;
}
}
return false;
}
private void addFree(Worker worker) {
if (worker == null) {
return;
}
Worker f = this.working.remove(worker.getId());
if (f == null) {
System.out.println("创建的worker加入free");
} else {
// System.out.println("从工作线程移入空闲集合");
}
this.free.put(worker.getId(), worker);
synchronized (isWait) {
this.isWait.notifyAll();
}
}
/***
* worker自己控制是否加入 free <br/>
*
* @author root
*
*/
static class Worker extends Thread {
private boolean run = false;
private Object runLock = new Object();
private boolean close = false;
private Runnable task;
private ThreadManager threadManager;
public Worker(ThreadManager threadManager) {
this.threadManager = threadManager;
this.start();// 启动线程
}
public void run() {
this.process();
}
private void process() {
while (!this.close) {
synchronized (runLock) {
try {
if (!this.isRun()) {// 空闲中加入free
this.threadManager.addFree(this);
this.runLock.wait();// 进行等待
if (this.close) {// 通知该worker结束
break;
}
}
} catch (InterruptedException e) {
}
}
this.run = true;
if (this.task != null) {
try {
this.task.run();
} catch (Exception ex) {// 保护工作线程不被异常结束
ex.printStackTrace();
}
} else {
System.out.println("#id=" + this.getId() + "线程声明的状态不对!");
}
// 重置变量变成空闲
this.run = false;
this.task = null;
}
System.out.println("工作线程终止 ");
}
public boolean isRun() {// 是否在运行任务
if (this.run && this.task != null) {
return true;
}
return false;
}
// 分配任务
public boolean handler(Runnable task) {
if (this.isRun()) {// 工作中
return false;
}
this.task = task;
synchronized (this.runLock) {
this.runLock.notifyAll();
}
return true;
}
// 关闭线程
public void close() {
this.close = true;
this.task = null;
synchronized (this.runLock) {
this.runLock.notifyAll();
}
}
}
public static void main(String[] args) throws IOException {
ThreadManager manager = new ThreadManager(3);
for (int i = 0; i < 20; i++) {
manager.execute(new T());
}
while (true) {
int ch = System.in.read();
if (ch == 'b') {
// 结束线程池
manager.close();
break;
} else {
System.out.println("增加新任务");
manager.execute(new T());// 增加任务
}
}
}
static class T implements Runnable {
T() {
}
public void run() {
System.out.println(this + "被工作线程执行,ID=" + Thread.currentThread().getId());
}
}
}