1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class MasterWorkerDemo {
static class Worker extends Thread { CountDownLatch latch; public Worker(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { Thread.sleep((int) (Math.random() * 1000)); if(Math.random() < 0.2) { throw new RuntimeException("bad luck"); } } catch(InterruptedException e) {
} finally { this.latch.countDown(); } } } public static void main(String[] args) throws InterruptedException { int workerNum = 100; CountDownLatch latch = new CountDownLatch(workerNum); Worker[] workers = new Worker[workerNum]; for(int i=0; i<workerNum; i++) { workers[i] = new Worker(latch); workers[i].start(); } latch.await(); System.out.println("collect worker results"); } }
|