Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ex1;
- import java.util.concurrent.locks.ReentrantReadWriteLock;;
- public class MySemaphore implements SemaphoreInterface {
- private int slots;
- private int waitingThreads;
- private ReentrantReadWriteLock l;
- public MySemaphore() {
- this.slots = 0;
- this.waitingThreads = 0;
- this.l = new ReentrantReadWriteLock();
- }
- @Override
- public synchronized void up() {
- l.writeLock().lock();
- slots++;
- l.writeLock().unlock();
- l.readLock().lock();
- int waiting = waitingThreads;
- l.readLock().unlock();
- if(waiting > 0) {
- l.writeLock().lock();
- waitingThreads--;
- l.writeLock().unlock();
- }
- notify(); // Notifying thread to wake up
- }
- @Override
- public synchronized void down() {
- l.readLock().lock();
- int s = slots;
- l.readLock().unlock();
- while (s == 0) {
- try {
- l.writeLock().lock();
- waitingThreads++;
- l.writeLock().unlock();
- wait(); // Blocking current thread
- } catch (InterruptedException exception) {
- exception.printStackTrace();
- }
- l.readLock().lock();
- s = slots;
- l.readLock().unlock();
- }
- l.writeLock().lock();
- slots--;
- l.writeLock().unlock();
- }
- @Override
- public synchronized int releaseAll() {
- l.readLock().lock();
- int tmp = waitingThreads;
- int waiting = waitingThreads;
- l.readLock().unlock();
- while(waiting > 0) {
- notify();
- l.writeLock().lock();
- waiting--;
- l.writeLock().unlock();
- }
- l.writeLock().lock();
- waitingThreads = 0;
- l.writeLock().unlock();
- l.writeLock().lock();
- slots += tmp;
- l.writeLock().unlock();
- return tmp;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement