Advertisement
MarlonKuqi

SPP_TP34_exo1

Feb 28th, 2019
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.97 KB | None | 0 0
  1. package ex1;
  2.  
  3. public class MySemaphore implements SemaphoreInterface {
  4.    
  5.     private int slots;
  6.     private int waitingThreads;
  7.  
  8.    
  9.     public MySemaphore() {
  10.         this.slots = 0;
  11.         this.waitingThreads = 0;
  12.     }
  13.  
  14.     @Override
  15.     public synchronized void up() {
  16.        
  17.         slots++;
  18.         int waiting = waitingThreads;
  19.         if(waiting > 0) {  
  20.             waitingThreads--;  
  21.         }
  22.         notify(); // Notifying thread to wake up
  23.     }
  24.  
  25.     @Override
  26.     public synchronized void down() {
  27.        
  28.         int s = slots;
  29.         while (s == 0) {
  30.             try {
  31.                 waitingThreads++;
  32.                 wait(); // Blocking current thread
  33.                 } catch (InterruptedException exception) {
  34.                     exception.printStackTrace();
  35.                 }
  36.                 s = slots; 
  37.             }
  38.             slots--;
  39.     }
  40.  
  41.     @Override
  42.     public synchronized int releaseAll() {
  43.        
  44.         int tmp = waitingThreads;
  45.         int waiting = waitingThreads;
  46.        
  47.         while(waiting > 0) {
  48.             notify();
  49.             waiting--;
  50.         }
  51.  
  52.         waitingThreads = 0;
  53.         slots += tmp;
  54.        
  55.         return tmp;
  56.     }
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement