代码比较简单,有助于理解线程池,代码如下:
public class ThreadPool {
private int maxCount;
private volatile boolean start = false;
private BlockingQueue<Runnable> tasks;
public ThreadPool() {
this(10);
}
public ThreadPool(int threadMaxCount) {
this.maxCount = threadMaxCount;
tasks = new LinkedBlockingQueue<Runnable>();
}
public void task(Runnable task) {
try {
tasks.put(task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void start() {
if (start)
return;
start = true;
for (int i = 0; i < maxCount; i++)
new Thread(new Runnable() {
@Override
public void run() {
try {
while (start)
tasks.take().run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public void stop() {
this.start = false;
}
}
测试代码如下:
public class App {
public static void main(String[] args) throws Exception {
ThreadPool tp = new ThreadPool();
tp.task(new Runnable() {
@Override
public void run() {
System.out.println("Begin");
}
});
tp.start();
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
tp.task(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread() + "doSomething!");
}
});
tp.stop();
}
}
}