_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();