Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 26: The Concurrency Utilities 803


cdl2.await();
cdl3.await();
cdl4.await();
} catch (InterruptedException exc) {
System.out.println(exc);
}

es.shutdown();
System.out.println("Done");
}
}


class MyThread implements Runnable {
String name;
CountDownLatch latch;


MyThread(CountDownLatch c, String n) {
latch = c;
name = n;

new Thread(this);
}

public void run() {

for(int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
latch.countDown();
}
}
}


The output from the program is shown here. (The precise order in which the threads
execute may vary.)


Starting
A: 0
A: 1
A: 2
A: 3
A: 4
C: 0
C: 1
C: 2
C: 3
C: 4
D: 0
D: 1
D: 2
D: 3
D: 4
B: 0
Free download pdf