237. Solving the producer-consumer problem via virtual threads
Let’s assume that we want to write a program simulating an assembly line (or a conveyor) for checking and packing bulbs using two workers. By checking, we mean that the worker tests if the bulb lights up or not. By packing, we mean that the worker takes the verified build and puts it in a box.
Next, let’s assume a fixed number of producers (3), and a fixed number of consumers (2); let’s represent it via the following diagram:
Figure 11.8: The producer-consumer problem with a fixed number of workers
We can implement this scenario via the well-known Executors.newFixedThreadPool(PRODUCERS)
, Executors.newFixedThreadPool(CONSUMERS)
, and ConcurrentLinkedQueue
as the temporary storage for checked bulbs, as you can see at https://github.com/PacktPublishing/Java-Coding-Problems/tree/master/Chapter10/P203_ThreadPoolFixed_ConcurrentLinkedQueue.
Let’s consider this code as legacy and...