public class SelfThreadPool {
//线程池中默认线程的个数为5
private static int WORK_NUM = 5;
//队列默认任务个数为100
private static int TASK_COUNT = 100;
//工作线程组
private WorkThread[] workThreads;
//任务队列
private final BlockingQueue<Runnable> queue;
private final int worker_num; //用户构造构造池子时希望启动的线程数
public SelfThreadPool() {
this(WORK_NUM, TASK_COUNT);
}
public SelfThreadPool(int worker_num, int taskCount) {
if (worker_num<=0) worker_num = WORK_NUM;
if(taskCount<=0) taskCount = TASK_COUNT;
this.worker_num = worker_num;
this.queue = new ArrayBlockingQueue<>(taskCount);
this.workThreads = new WorkThread[worker_num];
for (int i = 0; i < worker_num; i++) {
workThreads[i] = new WorkThread();
workThreads[i].start();
}
}
//执行任务,其中只是把任务加入队列,何时执行由线程池管理器决定
public void execute(Runnable task) {
try {
queue.put(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//销毁线程池,该方法保证在所有任务都完成的情况下才销毁线程池,否则等待任务完成才销毁
public void destroy() {
//工作线程停止,且置为null
System.out.println("ready close pool......");
for (int i = 0; i < worker_num; i++) {
workThreads[i].stopWorker();
workThreads[i] = null;
}
queue.clear();//清空任务队列
}
@Override
public String toString() {
return "WorkThread number: " + worker_num + " wait task number: " + queue.size();
}
/**
* 内部类,工作线程
*/
private class WorkThread extends Thread {
@Override
public void run() {
Runnable r = null;
try {
while (!isInterrupted()) {
r = queue.take();
if (r != null) {
System.out.println("Thread" + getId() + "is executing");
r.run();
}
r = null; //help gc
}
} catch (Exception e) {
}
}
public void stopWorker() {
interrupt();
}
}
}
public class SelfThreadPoolClient {
public static void main(String[] args) throws InterruptedException {
SelfThreadPool t = new SelfThreadPool(3, 0);
t.execute(new MyTask("testA"));
t.execute(new MyTask("testB"));
t.execute(new MyTask("testC"));
t.execute(new MyTask("testD"));
t.execute(new MyTask("testE"));
System.out.println(t);
Thread.sleep(10000);
t.destroy();// 所有线程都执行完成才destory
System.out.println(t);
}
// 任务类
static class MyTask implements Runnable {
private String name;
private Random r = new Random();
public MyTask(String name) {
this.name = name;
}
@Override
public void run() {// 执行任务
try {
Thread.sleep(r.nextInt(1000)+2000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getId()+" sleep InterruptedException:"
+Thread.currentThread().isInterrupted());
}
System.out.println("任务 " + name + " 完成");
}
}
}
//输出结果
Thread12 is executing
Thread13 is executing
WorkThread number: 3 wait task number: 2
Thread14 is executing
任务 testB 完成
Thread14 is executing
任务 testA 完成
Thread12 is executing
任务 testC 完成
任务 testD 完成
任务 testE 完成
ready close pool......
WorkThread number: 3 wait task number: 0