Advertisement
Guest User

Untitled

a guest
Jun 18th, 2018
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. import java.util.HashSet;
  2. import java.util.Set;
  3. import java.util.concurrent.locks.Condition;
  4. import java.util.concurrent.locks.ReentrantLock;
  5.  
  6. public class PortImplementacja implements Port {
  7.  
  8. private static ReentrantLock lock = new ReentrantLock();
  9. private static Condition cond = lock.newCondition();
  10.  
  11. private static int merchants = 0;
  12. private static Integer pirateId = null;
  13. private static Set<Integer> merchantsId = new HashSet<Integer>();
  14.  
  15. @Override
  16. public void kupiecIn(int id) {
  17. lock.lock();
  18. try {
  19. merchants++;
  20. while (merchants < 4 && pirateId != null) {
  21. cond.await();
  22. }
  23. merchantsId.add(id);
  24. merchants--;
  25. cond.signal();
  26. } catch (InterruptedException ignored) {
  27. } finally {
  28. lock.unlock();
  29. }
  30. }
  31.  
  32. @Override
  33. public void kupiecOut(int id) {
  34. lock.lock();
  35. try {
  36. while (!merchantsId.contains(id)) {
  37. cond.await();
  38. }
  39. merchantsId.remove(id);
  40. cond.signal();
  41. } catch (InterruptedException ignored) {
  42. } finally {
  43. lock.unlock();
  44. }
  45. }
  46.  
  47. @Override
  48. public void piratIn(int id) {
  49. lock.lock();
  50. try {
  51. while (!(merchantsId.isEmpty() && pirateId == null)) {
  52. cond.await();
  53. }
  54. pirateId = id;
  55.  
  56. cond.signal();
  57. } catch (InterruptedException ignored) {
  58. } finally {
  59. lock.unlock();
  60. }
  61. }
  62.  
  63. @Override
  64. public void piratOut(int id) {
  65. lock.lock();
  66. try {
  67. while (pirateId != id) {
  68. cond.await();
  69. }
  70. pirateId = null;
  71.  
  72. cond.signal();
  73. } catch (InterruptedException ignored) {
  74. } finally {
  75. lock.unlock();
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement