class MyThreadPool{
//描述一个类,直接使用Runnable
//使用一个数据结构来组着若干个任务
private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
//描述一个线程,工作线程的功能就是从任务队列中取任务并执行
static class Worker extends Thread{
//当前线程池中有若干个worker线程,这些线程内部都持有上述的任务队列
private BlockingQueue<Runnable> queue = null;
public Worker(BlockingQueue<Runnable> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true){
try {
//循环的获取任务队列中的任务
//如果队列为空直接阻塞,如果不为空,就获取里面的内容
Runnable runnable = queue.take();
//获取到之后,就执行任务
runnable.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//创建一个数据结构来组织若干个线程
private List<Thread> workers = new ArrayList<>();
public MyThreadPool(int n){
//在构造方法中创建若干个线程放到数组中
for (int i = 0; i < n; i++) {
Worker worker = new Worker(queue);
worker.start();
workers.add(worker);
}
}
//创建一个方法,允许程序员放任务到线程池中
public void submit(Runnable runnable){
try {
queue.put(runnable);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Day0813_2 {
public static void main(String[] args) {
MyThreadPool pool = new MyThreadPool(10);
for (int i = 0; i < 100; i++) {
pool.submit(new Runnable() {
@Override
public void run() {
System.out.println("hello threadpool");
}
});
}
}
}