准备工作:
- 需要一个任务仓库
- 集合容器,存放工作线程
- 普通线程要执行多个task,咱们需要封装一下
- 初始化线程池
- 对外提供提交任务的接口 非阻塞; 对外提供提交任务的接口 阻塞
- 关闭线程池
a. 禁止往队列提交任务
b. 等待仓库中的任务执行
c. 关闭的时候,再去那任务就不用阻塞,因为不会有新任务来了
d. 关闭的时候,阻塞的线程,就要强行中断阻塞/等待的线程
代码地址:
https://github.com/szwkang/tracylearn/tree/master/threadpool
代码展示:
package threadpoolimpl.fixedthreadpoolImpl.demo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
public class FixedThreadPool {
//定义pool是否shutdown
private boolean isShutDown = false;
//1.定义任务仓库
private LinkedBlockingQueue<Thread> queue;
//2.定义工作线程组
private List<Thread> threadWorkList;
//3.封装work thread
public static class WorkThread extends Thread {
private FixedThreadPool fixedThreadPool;
public WorkThread(FixedThreadPool pool) {
this.fixedThreadPool = pool;
}
@Override
public void run() {
while (!this.fixedThreadPool.isShutDown || this.fixedThreadPool.queue.size() > 0) {
Thread task = null;
try {
if (!this.fixedThreadPool.isShutDown)
task = this.fixedThreadPool.queue.take();
else
task = this.fixedThreadPool.queue.poll();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (task != null) {
task.run();
}
}
}
}
//4. init thread pool
public FixedThreadPool(int poolSize, int queueSize) {
if (poolSize <= 0 || queueSize <= 0) {
throw new IllegalArgumentException("illegal parameter");
}
this.threadWorkList = Collections.synchronizedList(new ArrayList<>(poolSize));
this.queue = new LinkedBlockingQueue<>(queueSize);
for (int i = 0; i < poolSize; i++) {
WorkThread workThread = new WorkThread(this);
workThread.start();
this.threadWorkList.add(workThread);
}
}
//5.1 non- block submit
public boolean nonBlockSubmit(Thread thread) {
if (this.isShutDown = false) {
return false;
}
return this.queue.offer(thread);
}
//5.2 block submit
public boolean blockSubmit(Thread thread) {
try {
if (this.isShutDown = false) {
return false;
}
this.queue.put(thread);
return true;
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
}
//6. 关闭线程池
a. 禁止往队列提交任务
b. 等待仓库中的任务执行
c. 关闭的时候,再去那任务就不用阻塞,因为不会有新任务来了
d. 关闭的时候,阻塞的线程,就要强行中断
public void shutdown() {
this.isShutDown = true;
for (Thread thread : this.threadWorkList) {
if (thread.getState().equals(Thread.State.BLOCKED) || thread.getState().equals(Thread.State.WAITING)
|| thread.getState().equals(Thread.State.TIMED_WAITING)) {
thread.interrupt();
}
}
}
}
如果还有什么不明白之处,请联系我啊