Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashSet;
- import java.util.Set;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.ReentrantLock;
- public class PortImplementacja implements Port {
- private static ReentrantLock lock = new ReentrantLock();
- private static Condition cond = lock.newCondition();
- private static int merchants = 0;
- private static Integer pirateId = null;
- private static Set<Integer> merchantsId = new HashSet<Integer>();
- @Override
- public void kupiecIn(int id) {
- lock.lock();
- try {
- merchants++;
- while (merchants < 4 && pirateId != null) {
- cond.await();
- }
- merchantsId.add(id);
- merchants--;
- cond.signal();
- } catch (InterruptedException ignored) {
- } finally {
- lock.unlock();
- }
- }
- @Override
- public void kupiecOut(int id) {
- lock.lock();
- try {
- while (!merchantsId.contains(id)) {
- cond.await();
- }
- merchantsId.remove(id);
- cond.signal();
- } catch (InterruptedException ignored) {
- } finally {
- lock.unlock();
- }
- }
- @Override
- public void piratIn(int id) {
- lock.lock();
- try {
- while (!(merchantsId.isEmpty() && pirateId == null)) {
- cond.await();
- }
- pirateId = id;
- cond.signal();
- } catch (InterruptedException ignored) {
- } finally {
- lock.unlock();
- }
- }
- @Override
- public void piratOut(int id) {
- lock.lock();
- try {
- while (pirateId != id) {
- cond.await();
- }
- pirateId = null;
- cond.signal();
- } catch (InterruptedException ignored) {
- } finally {
- lock.unlock();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement