Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Semaphore;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class SemaphorsLibrary {
- List<String> books = new ArrayList<>();
- int kapacitet;
- Semaphore koordinator = new Semaphore(1); //ni pomaga za kriticniot domen
- Semaphore returnBookSemaphor = new Semaphore(10);
- Semaphore borrowBookSemaphor = new Semaphore(10);
- public SemaphorsLibrary(int kapacitet) {
- this.kapacitet = kapacitet;
- }
- //slucaj koga clenot treba da vrati kniga vo bibliotekatta
- public void returnBook(String book) throws InterruptedException {
- returnBookSemaphor.acquire(); //ke dade kluc
- koordinator.acquire(); //zaklucuvame kriticen domen
- if (books.size() == kapacitet) {
- Thread.sleep(1000);
- koordinator.acquire();
- }
- books.add(book);
- koordinator.release(); //predadi kluc na dr
- borrowBookSemaphor.release();
- }
- //slucaj kgoa clenot treba da zeme kniga od bibliotekata
- public String borrowBook() throws InterruptedException {
- borrowBookSemaphor.acquire();
- String book = "";
- koordinator.acquire();
- while (books.size() == 0) {
- koordinator.release();
- Thread.sleep(1000);
- koordinator.acquire();
- }
- book = books.remove(0);
- returnBookSemaphor.release();
- return book;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement