1、前言
2、背景
3、线程池是一种生产者 - 消费者模式
如果让你通过对线程池的理解,自己动手实现一个简单的线程池,你该如何涉及与实现呢?
- 首先定义一个线程池的对象类
- 该对象类必须有两个基本属性:工作线程和工作队列
- 方法:构造方法、提交任务方法、工作线程方法
show you the code :
public class Client {
public static void main(String[] args) {
//使用线程池
MyThreadPool pool = new MyThreadPool(3, new LinkedBlockingQueue<>());
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("This is my runnable executed by thread pool");
}
};
pool.execute(runnable);
}
}
/**
* 简化的线程池,用来说明工作原理
*/
class MyThreadPool {
/**
* 利用阻塞队列来实现生产者-消费者模式
*/
BlockingQueue<Runnable> workQueue;
List<WorkThread> list = new ArrayList<>();
MyThreadPool(int poolSize, BlockingQueue<Runnable> blockingQueue) {
this.workQueue = blockingQueue;
//创建工作线程
for (int i = 0; i < poolSize; i++) {
WorkThread workThread = new WorkThread();
workThread.start();
list.add(workThread);
}
}
/**
* 提交任务
*
* @param command
*/
void execute(Runnable command) {
workQueue.add(command);
}
/**
* 工作线程,负责消费任务并执行任务
*/
class WorkThread extends Thread {
@Override
public void run() {
while (true) {
Runnable task = null;
try {
//循环取出,并执行任务
task = workQueue.take();
task.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}