import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class FixedSizeThreadPool {
//线程池的构成
//1.任务队列
private BlockingQueue<Runnable> blockingQueue;
//2.线程的集合
private List<Thread> workers;
//3.准备一个具体干活的线程
public static class Worker extends Thread{
private FixedSizeThreadPool pool;
public Worker(FixedSizeThreadPool pool) {
this.pool = pool;
}
@Override
public void run() {
//这里面该去执行,队列中 runnable的 run方法!
while (this.pool.isWorking || this.pool.blockingQueue.size()>0){
Runnable task = null;
try {
if(this.pool.isWorking){
task = this.pool.blockingQueue.take();//思考。--线程池的原理,没东西的时候阻塞
}else{
task = this.pool.blockingQueue.poll();//非阻塞
}
} catch (InterruptedException e) {
e.printStackTrace();
}
if(task!=null){
task.run();
System.out.println("线程:"+Thread.currentThread().getName());
}
}
}
}
// 4.构造方法
public FixedSizeThreadPool(int poolSize,int taskSize){
if(poolSize<=0 || taskSize<=0){
throw new IllegalArgumentException("非法参数");
}
this.blockingQueue= new LinkedBlockingQueue<>(taskSize);
this.workers= Collections.synchronizedList(new ArrayList<>());
for (int i=0;i<poolSize;i++){
Worker worker = new Worker(this);
worker.start();
workers.add(worker);
}
}
// 5.任务提交
public boolean submit(Runnable task){
if (isWorking){
return this.blockingQueue.offer(task);
}else{
return false;
}
}
// 6.关闭方法
// 思维方式 -- 基本法 --
// 1.任务提交这里,还需要提交吗? --- 提交不能提交了
// 2.任务队列里,还有任务没执行完? --- 执行完毕
// 3.一旦调用了 shutDown--- take() 阻塞, 不应该阻塞了
// 4.一旦有线程已经阻塞了呢? --- 中断
private volatile boolean isWorking = true;
public void shutDown(){
this.isWorking=false;
for (Thread thread: workers){
if(Thread.State.BLOCKED.equals(thread.getState())){
thread.interrupt();//线程中断
}
}
}
}
//测试类
public class TestDemo {
public static void main(String[] args) {
FixedSizeThreadPool pool=new FixedSizeThreadPool(3,6);
for (int i=0;i<6;i++)
{
pool.submit(new Runnable() {
@Override
public void run() {
System.out.println("放入一个线程~~~");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
pool.shutDown();
}
}