把上面的内容结合起来,就是一个SyncQueue的类:
public class SyncQueue {
public SyncQueue(int size) {
_array = new Object[size];
_size = size;
_oldest = 0;
_next = 0;
}
public synchronized void put(Object o) {
while (full()) {
try {
wait();
} catch (InterruptedException ex) {
throw new ExceptionAdapter(ex);
}
}
_array[_next] = o;
_next = (_next + 1) % _size;
notify();
}
public synchronized Object get() {
while (empty()) {
try {
wait();
} catch (InterruptedException ex) {
throw new ExceptionAdapter(ex);
}
}
Object ret = _array[_oldest];
_oldest = (_oldest + 1) % _size;
notify();
return ret;
}
protected boolean empty() {
return _next == _oldest;
}
protected boolean full() {
return (_next + 1) % _size == _oldest;
}
protected Object [] _array;
protected int _next;
protected int _oldest;
protected int _size;
}
可以注意一下get和put方法中while的使用,如果换成if是会有问题的。这是个很容易犯的错误。;-)
在以上代码中使用了ExceptionAdapter这个类,它的作用是把一个checked Exception包装成RuntimeException。详细的说明可以参考我的避免在Java中使用Checked Exception一文。
接下来我们需要一个对象来表现Thread缓冲池所要执行的任务。可以发现JDK中的Runnable interface非常合适这个角色。
最后,剩下工作线程的实现就很简单了:从SyncQueue里取出一个Runnable对象并执行它。
public class Worker implements Runnable {
public Worker(SyncQueue queue) {
_queue = queue;
}
public void run() {
while (true) {
Runnable task = (Runnable) _queue.get();
task.run();
}
}
protected SyncQueue _queue = null;
}
下面是一个使用这个Thread缓冲池的例子:
//构造Thread缓冲池
SyncQueue queue = new SyncQueue(10);
for (int i = 0; i < 5; i ++) {
new Thread(new Worker(queue)).start();
}
//使用Thread缓冲池
Runnable task = new MyTask();
queue.put(task);
为了使本文中的代码尽可能简单,这个Thread缓冲池的实现是一个基本的框架。当使用到实际中时,一些其他功能也可以在这一基础上添加,比如异常处理,动态调整缓冲池大小等等。




