【发布时间】:2012-07-20 04:38:48
【问题描述】:
我正在尝试实现一个图像缓存系统,该系统会在将 5 张图像插入缓存后暂停。
public void run() {
int index = 0;
lock.lock();
try {
while (index < list.getJpegCount() && !bCancel) {
String file = list.getJpeg(index);
images.put(file,
ImageUtils.getThumbNail(list.getJpeg(index), size));
index++;
batchCount++;
Console.writeLine("Object cached: " + file);
if (batchCount > 5) {
try {
batchCount = 0;
Console.writeLine("Waiting for next batch...");
bufferEmpty.await();
Console.writeLine("We are back...");
} catch (InterruptedException ex) {
Logger.getLogger(JpegCache.class.getName()).log(
Level.SEVERE, null, ex);
}
}
}
} finally {
lock.unlock();
}
}
现在的问题是我想使用以下方法唤醒线程,但它没有唤醒:
public Image getNext()
{
lock.lock();
currentIndex++;
String filename=list.getJpeg(currentIndex);
if (!images.containsKey(filename))
{
bufferEmpty.signalAll();
Console.writeLine("Start next batch...");
return ImageUtils.getThumbNail(filename, size);
}else
return images.get(filename);
}
怎么了?
【问题讨论】:
-
你是如何获得
bufferEmpty条件的? -
像这样:final Lock lock = new ReentrantLock();最终条件 bufferEmpty = lock.newCondition();
-
我最近在这里发布了pausing a thread 的机制。它可能很有趣。
-
你的代码太复杂了。应该有更简单的方法来使用监视器唤醒线程。
标签: java multithreading concurrency locking conditional-statements