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.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class MutexLibrary {
- List<String> books = new ArrayList<>();
- int kapacitet; //kolku knigi sobira vo bibliotekata
- public static Lock lock = new ReentrantLock();
- public MutexLibrary(int kapacitet) {
- this.kapacitet = kapacitet;
- }
- //slucaj koga clenot treba da vrati kniga vo bibliotekatta
- public void returnBook(String book) throws InterruptedException {
- lock.lock();
- while (true) {
- if (books.size() < kapacitet) {
- books.add(book);
- lock.unlock();
- break;
- }
- lock.unlock();
- }
- }
- //slucaj kgoa clenot treba da zeme kniga od bibliotekata
- public String borrowBook() throws InterruptedException {
- String book = "";
- while (true) {
- lock.lock();
- if (books.size() > 0) {
- book = books.remove(0);
- lock.unlock();
- break;
- }
- lock.unlock();
- }
- return book;
- }
- }
Add Comment
Please, Sign In to add comment