package com.tedu.data;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author xujs@inspur.com
*/
public class Test {
private static class Worker implements Runnable {
private BlockingQueue<Runnable> workQueue;
public Worker(BlockingQueue<Runnable> workQueue) {
this.workQueue = workQueue;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " start!");
while (true) {
try {
Runnable runnable = workQueue.take();
System.out.println(Thread.currentThread().getName() + " execute task");
runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static class ThreadPool {
private BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
private Worker[] workers;
public ThreadPool(int threadCount) {
workers = new Worker[threadCount];
for (int i = 0; i < threadCount; i++) {
workers[i] = new Worker(workQueue);
new Thread(workers[i], "worker" + i).start();
}
}
public void execute(Runnable runnable) {
try {
workQueue.put(runnable);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(3);
for (int i = 0; i < 100; i++) {
pool.execute(() -> {
System.out.println("this is a task");
});
}
}
}
程序的运行,其本质上,是对系统资源(CPU、内存、磁盘、网络等等)的使用。如何高效的使用这些资源是我们编程优化演进的一个方向。今天说的线程池就是一种对CPU利用的优化手段。
通过学习线程池原理,明白所有池化技术的基本设计思路。遇到其他相似问题可以解决。
池化技术
前面提到一个名词——池化技术,那么到底什么是池化技术呢?
池化技术简单点来说,就是提前保存大量的资源,以备不时之需。在机器资源有限的情况下,使用池化技术可以大大的提高资源的利用率,提升性能等。
在编程领域,比较典型的池化技术有:
线程池、连接池、内存池、对象池等。
本文主要来介绍一下其中比较简单的线程池的实现原理,希望读者们可以举一反三,通过对线程池的理解,学习并掌握所有编程中池化技术的底层原理。