简体   繁体   中英

Condition vs Semaphore in java concurrency

I'm having trouble getting my head around a homework problem. The question asks us to mimic the implementation of Condition by only using Semaphore as a concurrency control class and nothing else. Can someone point me in a direction by explaining exactly what the question is getting at

In the example MySemaphore.java, we implemented a Semaphore using Lock and Condition. Now, still keeping in the same spirit, implement a class MyCondition that works like Condition with methods await and signal (no need to implement the rest of the methods here). In your implementation, the only concurrency control class that you are allowed to use is Semaphore.

Here's the example referred to in the question

import java.util.concurrent.locks.*;

// A standard exercise of Concurrency 101 is to show that Semaphores are
// equivalent to Locks and Condition Variables in power, by implementing
// one with the other. Here, a simple Semaphore implementation.

public class MySemaphore {
    private int permits;
    private Lock mutex;
    private Condition permitAvailable;

    public MySemaphore(int permits, boolean fair) {
        this.permits = permits;
        this.mutex = new ReentrantLock(fair);
        this.permitAvailable = mutex.newCondition();
    }

    public void acquire() throws InterruptedException {
        mutex.lock();
        try {
            while(permits < 1) {
                // Wait for one permit to become available.
                permitAvailable.await();
            }
            permits--;
        }
        // Ensure that mutex is unlocked even if an exception is thrown.
        finally { mutex.unlock(); }
    }

    public void release() {
        mutex.lock();
        permits++;
        // One waiting thread can now acquire a permit.
        permitAvailable.signal();
        mutex.unlock();
    }
}

If this is your homework, check source code of Lock & Condition & Semaphore of j2se first. Then try implement it, in that way your homework make sense, it make you understand the mechanism.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM