线程池用有限的线程执行无限的任务。我很好奇,这是如何实现的?在看了一些博文和简单的阅读了一下JDK线程池的源代码后,终于明白,原来就是:首先,创建固定数量的线程,然后,这些线程执行提交的Runnable的run方法。基于这个理解,我实现了一个极简的线程池:
package threadpool;
import java.util.LinkedList;
/**
* 简单的Java线程池
*
* @author liyuncong
*
*/
public class SimpleThreadPool {
private LinkedList<Worker> workers;
private LinkedList<Runnable> tasks;
private State state = State.RUNNING;
public SimpleThreadPool(int threadPoolSize) throws IllegalAccessException {
if (threadPoolSize < 1) {
throw new IllegalAccessException("线程池大小至少为1");
}
workers = new LinkedList<>();
tasks = new LinkedList<>();
for (int i = 0; i < threadPoolSize; i++) {
Worker worker = new Worker(this);
worker.start();
workers.add(worker);
}
}
public synchronized void execut(Runnable task) {
if (this.state == State.RUNNING) {
this.tasks.add(task);
notifyAll();
}
}
public synchronized Runnable getNewTask() {
while (tasks.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return tasks.remove();
}
public synchronized void shutdown() {
if (this.state == State.TERMINATION) {
return;
}
this.state = State.TERMINATION;
for (Worker worker : workers) {
worker.interrupt();
}
}
private static class Worker extends Thread {
private SimpleThreadPool simpleThreadPool;
public Worker(SimpleThreadPool simpleThreadPool) {
this.simpleThreadPool = simpleThreadPool;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
simpleThreadPool.getNewTask().run();
}
}
}
private static enum State {
RUNNING, TERMINATION;
}
}
package threadpool;
public class TestSimpleThreadPool {
public static void main(String[] args) throws IllegalAccessException {
final SimpleThreadPool simpleThreadPool = new SimpleThreadPool(3);
for (int i = 0; i < 10; i++) {
int j = i;
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-task" + j);
}
};
simpleThreadPool.execut(task);
if (j == 7) {
simpleThreadPool.shutdown();
}
}
}
}
欢迎大家吐槽我的理解和示例。