如何使用锁定和一个条件暂停/恢复?

时间:2012-07-20 21:32:00

标签: java multithreading concurrency locking conditional-statements

我正在尝试实现一个图像缓存系统,它会在将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);

}

怎么了?

1 个答案:

答案 0 :(得分:0)

解决方案:

我忘了打开锁:

public Image getNext()
{        
    lock.lock();
    currentIndex++; 
    String filename=list.getJpeg(currentIndex);
    if (!images.containsKey(filename))
    {
        bufferEmpty.signalAll();
        lock.unlock();
        Console.writeLine("Start next batch...");
        return ImageUtils.getThumbNail(filename, size);           

    }else
    {
        lock.unlock();
        return images.get(filename);
    }
}
相关问题