如何在Java中恰当地使用条件?

How to use condition appropriately in Java?

我的两个线程 Produce 和 Consume 运行不正常。当我 运行 这段代码时,控制台一一打印 'producing' 和 'consuming' 。然后,它停止了,程序仍然是 运行ning>

class BufferMutex {
    private char [] buffer;
    private int count = 0, in = 0, out = 0;
    private ReentrantLock mutex = new ReentrantLock();
    private Condition okProduce = mutex.newCondition(); 
    private Condition okConsume = mutex.newCondition(); 

    BufferMutex(int size) {
        buffer = new char[size];
    }

    public void put(char c) {
        mutex.lock();
        try {
            while(count == buffer.length) { 
                okProduce.await();
            }
            System.out.println("Producing " + c + " ...");
            buffer[in] = c;
            in = (in + 1) % buffer.length;
            count++;
            okProduce.signalAll();
        }catch(InterruptedException ie) {
            ie.printStackTrace();
        }finally {
            mutex.unlock();
        }
    }

    public char get() {
        mutex.lock();
        char c = buffer[out];
        try {
            while (count == 0) {  
                okConsume.await();
            }
            out = (out + 1) % buffer.length;
            count--;
            System.out.println("Consuming " + c + " ...");
            okConsume.signalAll();
        }catch(InterruptedException ie) {
            ie.printStackTrace();
        }finally {
            mutex.unlock();
        }
        return c;
    }
}

您似乎让生产者向生产者发出信号,而消费者向消费者发出信号。你不想换这些吗?生产者不应该向消费者发出信号,反之亦然吗?