Advertisement
ivana_andreevska

Sinhronizacija so pomos na Semaphor

Mar 14th, 2022
1,139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.concurrent.Semaphore;
  4. import java.util.concurrent.locks.Lock;
  5. import java.util.concurrent.locks.ReentrantLock;
  6.  
  7. public class SemaphorsLibrary {
  8.     List<String> books = new ArrayList<>();
  9.     int kapacitet;
  10.  
  11.     Semaphore koordinator = new Semaphore(1); //ni pomaga za kriticniot domen
  12.     Semaphore returnBookSemaphor = new Semaphore(10);
  13.     Semaphore borrowBookSemaphor = new Semaphore(10);
  14.  
  15.     public SemaphorsLibrary(int kapacitet) {
  16.         this.kapacitet = kapacitet;
  17.     }
  18.  
  19.     //slucaj koga clenot treba da vrati kniga vo bibliotekatta
  20.     public void returnBook(String book) throws InterruptedException {
  21.         returnBookSemaphor.acquire(); //ke dade kluc
  22.         koordinator.acquire(); //zaklucuvame kriticen domen
  23.         if (books.size() == kapacitet) {
  24.             Thread.sleep(1000);
  25.             koordinator.acquire();
  26.         }
  27.         books.add(book);
  28.         koordinator.release(); //predadi kluc na dr
  29.         borrowBookSemaphor.release();
  30.     }
  31.  
  32.  
  33.     //slucaj kgoa clenot treba da zeme kniga od bibliotekata
  34.     public String borrowBook() throws InterruptedException {
  35.         borrowBookSemaphor.acquire();
  36.         String book = "";
  37.         koordinator.acquire();
  38.         while (books.size() == 0) {
  39.             koordinator.release();
  40.             Thread.sleep(1000);
  41.             koordinator.acquire();
  42.         }
  43.         book = books.remove(0);
  44.         returnBookSemaphor.release();
  45.         return book;
  46.     }
  47.  
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement