package com.devart.appinterface.common;
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{
//相当于每个worker都有相应的线程池
private FixedSizeThreadPool pool;
public Worker(FixedSizeThreadPool pool){
this.pool=pool;
}
@Override
public void 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 fixedSize,int taskSize){
if(fixedSize<=0 || taskSize<=0){
throw new IllegalArgumentException("非法参数");
}
this.blockingQueue=new LinkedBlockingQueue<>(taskSize);
this.workers= Collections.synchronizedList(new ArrayList<>());
for(int i=0;i<fixedSize;i++){
Worker worker=new Worker(this);
worker.start();
workers.add(worker);
}
}
//5.需要向我们仓库放任务的方法,不柱塞
public boolean submit(Runnable task){
if(this.isWorking){
return this.blockingQueue.offer(task);
}else{
return false;
}
}
//6.需要向我们仓库放任务的方法,柱塞
public void execute(Runnable task){
try {
this.blockingQueue.put(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//7.需要一个关闭烧线程的方法
//a.关闭的时候,仓库不再添加新的
//b.关闭的时候,运行完仓库里面的
//c.关闭的时候,如果去仓库拿东西,那么就不再堵塞了
//d.关闭的时候,如果有堵塞的那么就中断掉
private volatile boolean isWorking=true;
public void shutDown(){
this.isWorking=false;
for(Thread thread:workers){
if(thread.getState().equals(Thread.State.BLOCKED)||thread.getState().equals(Thread.State.WAITING)){
thread.interrupt();
}
}
}
public static void main(String[] args) {
FixedSizeThreadPool pool=new FixedSizeThreadPool(3,6);
for (int j=0;j<6;j++){
pool.submit(new Runnable() {
@Override
public void run() {
System.out.println("一个线程被放到我们的仓库中");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("一个线程被唤醒");
}
}
});
}
pool.shutDown();
}
}
FixedThreadPool实现思路与步骤
最新推荐文章于 2024-07-04 09:37:28 发布