1 package ch.hslu.exercises.sw08.ex4;
2
3 import java.util.*;
4 import java.util.concurrent.ExecutionException;
5 import java.util.concurrent.ExecutorService;
6 import java.util.concurrent.Executors;
7 import java.util.concurrent.Future;
8
9 import org.slf4j.LoggerFactory;
10 import org.slf4j.Logger;
11
12
13
14
15 public final class DemoConcurrentList {
16
17 private static final Logger LOG = LoggerFactory.getLogger(DemoConcurrentList.class);
18
19
20
21
22 private DemoConcurrentList() {
23 }
24
25
26
27
28
29
30
31
32 public static void main(final String[] args) throws InterruptedException, ExecutionException {
33 final List<Integer> list = Collections.synchronizedList(new ArrayList<>());
34 final List<Future<Long>> futures = new ArrayList<>();
35 try (final ExecutorService executor = Executors.newCachedThreadPool()) {
36 for (int i = 0; i < 3; i++) {
37 futures.add(executor.submit(new Producer(list, 1000)));
38 }
39 Iterator<Future<Long>> iterator = futures.iterator();
40 long totProd = 0;
41 while (iterator.hasNext()) {
42 long sum = iterator.next().get();
43 totProd += sum;
44 LOG.info("prod sum = {}", sum);
45 }
46 LOG.info("prod tot = {}", totProd);
47 long totCons = executor.submit(new Consumer(list)).get();
48 LOG.info("cons tot = {}", totCons);
49 }
50 }
51 }