Facebook
From Gentle Gorilla, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 250
  1. package Paradigms.List11.CommonStaticVariableResolvings;
  2.  
  3.  
  4.  
  5. import java.util.concurrent.Semaphore;
  6.  
  7.  
  8.  
  9. class CountSemaphore extends Thread{
  10.  
  11.     static IntCellDefault n = new IntCellDefault();
  12.  
  13.     private static Semaphore mutex = new Semaphore(1, true);
  14.  
  15.     // first arg permit = liczba pozwolen, definiuje liczbe watkow ktora w jednym czasie moze uzyskac dostep do
  16.  
  17.     // sekcji krytycznej, maleje ona w dol
  18.  
  19.     // second arg fair = uczciowosc, polegajaca na szeregowaniu watkow oczekujacych na dostep do sekcji krytycznej
  20.  
  21.     // przy pomocy kolejki FIFO
  22.  
  23.     // nazwa zmiennej mutex poniewaz semaphore z umozliwiajacy tylko jedno pozwolenie jest semaforem binarnym czyli
  24.  
  25.     // tzw. mutexem
  26.  
  27.  
  28.  
  29.     @Override
  30.  
  31.     public void run(){
  32.  
  33.         for (int i = 0; i < 200000; i++){
  34.  
  35.             tryAcquire();
  36.  
  37.             int temp = n.getN();
  38.  
  39.             n.setN(temp+1);
  40.  
  41.             mutex.release();
  42.  
  43.         }
  44.  
  45.     }
  46.  
  47.  
  48.  
  49.     private void tryAcquire(){
  50.  
  51.         try{
  52.  
  53.             mutex.acquire();
  54.  
  55.         }catch(InterruptedException e){
  56.  
  57.             e.printStackTrace();
  58.  
  59.         }
  60.  
  61.     }
  62.  
  63.  
  64.  
  65.     public static void main(String[] args){
  66.  
  67.         CountSemaphore thread1 = new CountSemaphore();
  68.  
  69.         CountSemaphore thread2 = new CountSemaphore();
  70.  
  71.         thread1.start();
  72.  
  73.         thread2.start();
  74.  
  75.         try{
  76.  
  77.             thread1.join();
  78.  
  79.             thread2.join();
  80.  
  81.         }catch(InterruptedException e){
  82.  
  83.             System.out.println(e.getStackTrace());
  84.  
  85.             System.out.println("Catched exception");
  86.  
  87.         }
  88.  
  89.         System.out.println("The value of n is " + n.getN());
  90.  
  91.         System.out.println("Used semaphore");
  92.  
  93.     }
  94.  
  95. }