UPDATE
I'm solving a producer / consumer problem, and I want to create a few producers and consumers (several threads) and I have a question how can I create several threads correctly so that one task is not performed by two threads (each thread does a different task).
code: I tried to do it just in a loop like here:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(10);
for (int i = 0; i < 10 ; i++) {
Producer producer = new Producer(blockingQueue);
Consumer consumer = new Consumer(blockingQueue);
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}
}
output: but it doesn't work because the threads are overlapping each other
Producer produced : 1619703940537
Producer produced : 1619703940537
Producer produced : 1619703940537
Producer produced : 1619703940537
consumed gets: 1619703940537
consumed gets: 1619703940537
consumed gets: 1619703940537
consumed gets: 1619703940537
Producer produced : 1619703940537
consumed gets: 1619703940537