【问题标题】:How can i pause/resume using lock and one condition?如何使用锁定和一种条件暂停/恢复?
【发布时间】: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


【解决方案1】:

解决方案:

我忘记开锁了:

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);
    }
}

【讨论】:

  • 你应该总是在 finally 块中解锁!
猜你喜欢
  • 1970-01-01
  • 2010-10-19
  • 2018-04-08
  • 2016-10-07
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多