import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* 簡化的線程池,僅用來說明工作原理.<br>
* @author gongqiang <br>
* @version 1.0.0 2021年6月9日<br>
* @see
* @since JDK 1.5.0
*/
public class MyThreadPool {
// 利用阻塞隊列實作生産者 - 消費者模式
private BlockingQueue<Runnable> workQueue;
// 儲存内部工作線程
private List<WorkerThread> threads = new ArrayList<>();
// 構造方法
public MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue){
this.workQueue = workQueue;
// 建立工作線程
for(int idx=0; idx<poolSize; idx++){
WorkerThread work = new WorkerThread();
work.start();
threads.add(work);
}
}
// 送出任務
void execute(Runnable command){
try {
workQueue.put(command);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 工作線程負責消費任務,并執行任務
class WorkerThread extends Thread{
public void run() {
// 循環取任務并執行
while(true){
try {
Runnable task = workQueue.take();
task.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
/**
* 示例.
* @param args
*/
public static void main(String[] args) {
// 建立有界阻塞隊列
final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2);
// 建立線程池
MyThreadPool pool = new MyThreadPool(10, workQueue);
// 送出任務
pool.execute(()->{
System.out.println("hello");
});
}
}