1. 消费-生产模式
2. 代码实现
package com.sz;
import java.util.HashSet;
import java.util.concurrent.BlockingQueue;
public class SimPlePool {
//单向阻塞队列
BlockingQueue<Runnable> queue;
//工作线程容器
HashSet<workThread> works = new HashSet<>();
public SimPlePool(int coreSize,BlockingQueue queue) {
this.queue = queue;
coreSize=coreSize<=0?1:coreSize;
//创建核心线程
for (int i = 0; i < coreSize; i++) {
workThread workThread = new workThread();
workThread.start();
works.add(workThread);
}
}
public void execute(Runnable r){
try {
queue.put(r);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
class workThread extends Thread{
/**
* 队列操作三组命令
* add remove 抛出异常
* put take 满或空 都阻塞
* offer pool 返回true 或 false
* peek 查看队首元素,不移出
*/
public void run() {
//从阻塞队列中获取线程
while (true) {
Runnable r;
try {
r = queue.take();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
r.run();
}
}
}
}