Guest User

Untitled

a guest
Apr 21st, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. public class Manage {
  2.  
  3. private Object lock = new Object();
  4. private LinkedList<Integer> intStorage = new LinkedList<Integer>();
  5. private LinkedList<Integer> evens = new LinkedList<>();
  6. private LinkedList<Integer> odds = new LinkedList<>();
  7.  
  8. public void intCollection() throws InterruptedException {
  9.  
  10. for (int i = 0; i < 20; i++) {
  11.  
  12. synchronized(lock) {
  13.  
  14. while(i == m) {
  15. lock.wait();
  16. }
  17.  
  18. intStorage.add(i);
  19. LocalLock.notifyAll();
  20. System.out.println(intStorage);
  21. }
  22. Thread.sleep(100);
  23. }
  24. }
  25.  
  26. public void evens() throws InterruptedException {
  27.  
  28. for(int i = 0; i < intStorage.size() ; i++) {
  29.  
  30. synchronized(lock) {
  31.  
  32. if(intStorage.get(i) % 2 != 0) {
  33. lock.wait();
  34. }
  35.  
  36. if(intStorage.get(i) % 2 == 0) {
  37. int j = intStorage.remove(i);
  38. evens.add(j);
  39. lock.notifyAll();
  40. }
  41. System.out.println(evens);
  42. }
  43. Thread.sleep(1000);
  44. }
  45.  
  46. }
  47.  
  48. public void odds() throws InterruptedException {
  49.  
  50. for(int i = 0; i < intStorage.size() ; i++) {
  51.  
  52. synchronized(lock) {
  53.  
  54. if(intStorage.get(i) % 2 == 0) {
  55. lock.wait();
  56. }
  57.  
  58. if(intStorage.get(i) % 2 != 0) {
  59. int j = intStorage.remove(i);
  60. odds.add(j);
  61. lock.notifyAll();
  62. }
  63. System.out.println(odds);
  64. }
  65. Thread.sleep(1000);
  66. }
  67.  
  68. }
  69.  
  70. public static void main(String[] args) throws InterruptedException {
  71.  
  72. Manager m = new Manager();
  73.  
  74. Thread t1 = new Thread(){
  75. public void run() {
  76. try {
  77. m.intCollection();
  78. } catch (InterruptedException e) {
  79. }
  80. }
  81. };
  82.  
  83. Thread t2 = new Thread(){
  84. public void run() {
  85. try {
  86. m.evens();
  87. } catch (InterruptedException e) {
  88. }
  89. }
  90. };
  91. Thread t3 = new Thread(){
  92. public void run() {
  93. try {
  94. m.odds();
  95. } catch (InterruptedException e) {
  96. }
  97. }
  98. };
  99.  
  100. t1.start();
  101. t2.start();
  102. t3.start();
  103.  
  104. t1.join();
  105. t2.join();
  106. t3.join();
  107.  
  108. }
Add Comment
Please, Sign In to add comment