203. Thread pool with a fixed number of threads

This problem reiterates the scenario from the Thread pool with a single thread section. This time, the assembly line uses three producers and two consumers, as in the following diagram:

We can rely on Executors.newFixedThreadPool​(int nThreads) to simulate the fixed number of producers and consumers. We allocate one thread per producer (respectively, consumer), therefore the code is pretty simple:

private static final int PRODUCERS = 3;
private static final int CONSUMERS = 2;
private static final Producer producer = new Producer();
private static final Consumer consumer = new Consumer();
private static ExecutorService producerService;
private static ExecutorService consumerService;
...
producerService = Executors.newFixedThreadPool(PRODUCERS);
for (int i = 0; i < PRODUCERS; i++) {
producerService.execute(producer);
}

consumerService = Executors.newFixedThreadPool(CONSUMERS);
for (int i = 0; i < CONSUMERS; i++) {
consumerService.execute(consumer);
}

The queue in which the producers can add the checked bulbs can be of the LinkedTransferQueue or ConcurrentLinkedQueue type, and so on.

The complete source code based on LinkedTransferQueue and ConcurrentLinkedQueue can be found in the code bundled with this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.209.201