Synchronisation mit Latch

final int threads = 4; 
final long top = 1000000000L;
final BigInteger [] s = new BigInteger[threads];
final CountDownLatch c = new CountDownLatch(threads);
for (int t=0; t<threads; t++) {
        final int start = t;
        new Thread(new Runnable() {
                public void run() {
                        BigInteger a = BigInteger.valueOf(0L);
                        for (long i = start; i<top; i+=threads) {
                                a = a.add(BigInteger.valueOf(i));
                        }
                        s[start] = a;
                        System.out.println("thread " + start + " resultat " + a);
                        c.countDown();
                } }).start ();
}
c.await ();
BigInteger total = BigInteger.ZERO;
for (int t = 0; t<threads; t++) { 
        total = total.add (s[t]); 
}
System.out.println(total);


Johannes Waldmann 2012-01-31