public class SimpleThreadPool {
private final int size;
private final static int DEFAULT_SIZE = 10;
private static volatile int seq = 0;
private final static String THREAD_PREFIX = "SIMPLE_THREAD_POOL-";
private final static ThreadGroup GROUP = new ThreadGroup("Pool_Group");
private final static LinkedList<Runnable> TASK_QUEUE = new LinkedList<>(); //任务队列!
private final static List<WorkerTask> THREAD_QUEUE = new ArrayList<>(); //模拟线程池!
public SimpleThreadPool(){
this(DEFAULT_SIZE);
}
public SimpleThreadPool(int size){
this.size = size;
init();
}
private void init() {
for (int i = 0; i < size; i++) {
createWorkThread();
}
}
//使用public权限修饰符对外提供接口
public void submit(Runnable runnable){
//写操作
synchronized (TASK_QUEUE){
TASK_QUEUE.addLast(runnable);
TASK_QUEUE.notifyAll();
}
}
private void createWorkThread(){
WorkerTask task = new WorkerTask(GROUP, THREAD_PREFIX+(seq++));
task.start();
THREAD_QUEUE.add(task);
}
//使用枚举定义线程的状态
private enum TaskState{
FREE,RUNNING,BLOCKED,DEAD //空闲,运行,阻塞,死亡
}
//静态内部类
private static class WorkerTask extends Thread{
private volatile TaskState taskState = TaskState.FREE;//默认是空闲
public WorkerTask(ThreadGroup threadGroup, String name){
super(threadGroup,name);
}
public TaskState getTaskState(){
return this.taskState;
}
public void close(){
this.taskState = TaskState.DEAD;
}
@Override
public void run() {
OUTER:
while(TaskState.DEAD != this.taskState){
Runnable runnable;
synchronized (TASK_QUEUE){
while(TASK_QUEUE.isEmpty()){
try {
//任务队列中没有任务,我就等待
this.taskState = TaskState.BLOCKED;
TASK_QUEUE.wait();
} catch (InterruptedException e) {
break OUTER; //直接跳到最外层循环!
}
}
runnable = TASK_QUEUE.removeFirst();
}
if(runnable != null){
this.taskState = TaskState.RUNNING;
runnable.run();
this.taskState = TaskState.FREE; //运行完之后变成空闲的,而不是杀死!
}
}
}
}
public static void main(String[] args) {
SimpleThreadPool simpleThreadPool = new SimpleThreadPool();
for (int i = 0; i < 40; i++) {
simpleThreadPool.submit(() ->{
System.out.println("The Runnable be service by "+Thread.currentThread()+" start");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The Runnable be service by "+Thread.currentThread()+" end");
});
}
}
}
```java
简单线程池
最新推荐文章于 2022-07-30 18:33:12 发布