View Javadoc
1   package ch.hslu.exercises.sw06.ex4;
2   
3   import java.util.Random;
4   import java.util.concurrent.TimeUnit;
5   
6   import org.slf4j.LoggerFactory;
7   import org.slf4j.Logger;
8   
9   /**
10   * Demonstration des BoundedBuffers mit n Producer und m Consumer.
11   */
12  public final class DemoBoundedBuffer {
13  
14      private static final Logger LOG = LoggerFactory.getLogger(DemoBoundedBuffer.class);
15  
16      /**
17       * Privater Konstruktor.
18       */
19      private DemoBoundedBuffer() {
20      }
21  
22      /**
23       * Main-Demo.
24       *
25       * @param args not used.
26       * @throws InterruptedException wenn das warten unterbrochen wird.
27       */
28      public static void main(final String args[]) throws InterruptedException {
29          final Random random = new Random();
30          final int nPros = 3;
31          final Producer[] producers = new Producer[nPros];
32          final ThreadGroup prosGroup = new ThreadGroup("Producer-Threads");
33          final int mCons = 2;
34          final Consumer[] consumers = new Consumer[mCons];
35          final ThreadGroup consGroup = new ThreadGroup("Consumer-Threads");
36          final BoundedBuffer<Integer> queue = new BoundedBuffer<>(50);
37          for (int i = 0; i < nPros; i++) {
38              producers[i] = new Producer(queue, random.nextInt(10000));
39              new Thread(prosGroup, producers[i], "Prod  " + (char) (i + 65)).start();
40          }
41          for (int i = 0; i < mCons; i++) {
42              consumers[i] = new Consumer(queue);
43              new Thread(consGroup, consumers[i], "Cons " + (char) (i + 65)).start();
44          }
45          while (prosGroup.activeCount() > 0) {
46              Thread.yield();
47          }
48          TimeUnit.MILLISECONDS.sleep(100);
49          consGroup.interrupt();
50          long sumPros = 0;
51          for (int i = 0; i < nPros; i++) {
52              LOG.info("Prod {} = {}", (char) (i + 65), producers[i].getSum());
53              sumPros += producers[i].getSum();
54          }
55          long sumCons = 0;
56          for (int i = 0; i < mCons; i++) {
57              LOG.info("Cons {} = {}", (char) (i + 65), consumers[i].getSum());
58              sumCons += consumers[i].getSum();
59          }
60          LOG.info("{} = {}", sumPros, sumCons);
61          LOG.info("queue size = {}", queue.size());
62          LOG.info("queue empty? {}", queue.empty());
63      }
64  }