Home > Enterprise >  How to use condition appropriately in Java?
How to use condition appropriately in Java?

Time:05-19

My two Threads, Produce and Consume, don't work well. When I run this code, the console printed 'producing' and 'consuming' one by one. Then, it stopped and program is still running>

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

CodePudding user response:

You seem to have the producer signalling the producer and the consumer signalling the consumer. Don't you want to switch those? Shouldn't the producer signal the consumer and vice versa?

  • Related