原文: link.
创建ThreadPool
package threadpool;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
public class MyThreadPool {
private final static int WORK_NUM = 5;
private final static int TASK_NUM = 100;
private int work_num;
private int task_num;
private final Set<WorkThread> workThreads;
private final BlockingQueue<Runnable> taskQueue;
public MyThreadPool(){
this(WORK_NUM, TASK_NUM);
}
public MyThreadPool(int work_num, int task_num){
if(work_num <= 0) work_num = WORK_NUM;
if(task_num <= 0) task_num = TASK_NUM;
this.work_num = work_num;
this.task_num = task_num;
workThreads = new HashSet<>();
taskQueue = new ArrayBlockingQueue<>(task_num);
for(int i = 0; i < work_num; i++){
WorkThread workThread = new WorkThread("thread_" + i);
workThread.start();
workThreads.add(workThread);
}
}
public void execute(Runnable task){
try {
taskQueue.put(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void destory(){
System.out.println("ready close thread pool...");
if(workThreads == null || workThreads.isEmpty()) return;
for(WorkThread workThread : workThreads){
workThread.stopWork();
workThread = null;
}
workThreads.clear();
}
private class WorkThread extends Thread{
public WorkThread(String name){
super();
setName(name);
}
@Override
public void run(){
while(!interrupted()){
try {
Runnable runnable = taskQueue.take();
if(runnable != null){
System.out.println(getName()+" ready execute:"+runnable.toString());
runnable.run(); }
runnable = null;
}catch (Exception e){
interrupt();
e.printStackTrace();
}
}
}
public void stopWork(){
interrupt();
}
}
}
测试
package threadpool;
public class TestThreadPool {
private static final int TASK_NUM = 50;
public static void main(String[] args){
MyThreadPool mypool = new MyThreadPool(3, 50);
for(int i = 0; i < TASK_NUM; i++){
mypool.execute(new myTask("task_" + i));
}
}
static class myTask implements Runnable{
private String name;
public myTask(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
@Override
public void run(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("task :" + name + " end...");
}
@Override
public String toString(){
return "name = " + name;
}
}
}