1 package com.freemindcafe.concurrency.sample5;
4 import java.util.concurrent.CopyOnWriteArrayList;
5 import java.util.concurrent.Semaphore;
6 import java.util.concurrent.locks.Condition;
7 import java.util.concurrent.locks.Lock;
8 import java.util.concurrent.locks.ReentrantLock;
9 import java.util.function.Consumer;
14 public void test_with_out_coordination()
throws Exception{
16 List<Integer> firstTenInts =
new CopyOnWriteArrayList<>();
19 for(
int i=0; i <=4; i++){
20 firstTenInts.add(2*i+1);
25 for(
int i=1; i <=5; i++){
26 firstTenInts.add(2*i);
30 Thread t1 =
new Thread(r1);
31 Thread t2 =
new Thread(r2);
39 System.out.println(firstTenInts);
45 public void test_with_coordination_using_semaphore()
throws Exception{
46 Semaphore firstOneDone =
new Semaphore(0);
47 Semaphore secondOneDone =
new Semaphore(0);
48 List<Integer> firstTenInts =
new CopyOnWriteArrayList<>();
52 for(
int i=0; i <=4; i++){
54 firstTenInts.add(2*i+1);
55 firstOneDone.release();
56 secondOneDone.acquire();
60 throw new RuntimeException(ex);
66 for(
int i=1; i <=5; i++){
68 firstOneDone.acquire();
69 firstTenInts.add(2*i);
70 secondOneDone.release();
74 throw new RuntimeException(ex);
78 Thread t1 =
new Thread(r1);
79 Thread t2 =
new Thread(r2);
87 System.out.println(firstTenInts);
94 public void test_with_coordination_using_condition()
throws Exception{
95 Lock lock =
new ReentrantLock();
96 Condition firstOneDone = lock.newCondition();
97 Condition secondOneDone = lock.newCondition();
98 List<Integer> firstTenInts =
new CopyOnWriteArrayList<>();
100 Runnable r1 = () -> {
102 for(
int i=0; i <=4; i++){
104 firstTenInts.add(2*i+1);
105 firstOneDone.signal();
106 secondOneDone.wait();
110 throw new RuntimeException(ex);
114 Runnable r2 = () -> {
116 for(
int i=1; i <=5; i++){
119 firstTenInts.add(2*i);
120 secondOneDone.signal();
124 throw new RuntimeException(ex);
128 Thread t1 =
new Thread(r1);
129 Thread t2 =
new Thread(r2);
137 System.out.println(firstTenInts);
140 } <T> Block<T> exceptionWrappingBlock(Block<T> b) {
143 catch (Exception ex) {
throw new RuntimeException(ex); }
150 void accept() throws Exception;