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