Skip to content

creating multiple threads with a unique id (threads do not overlap)

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

Answer

You are seeing several threads use same value of System.currentTimeMillis() which makes it impossible to tell what is going on. Change the token you pass into the queue to be unique PER Producer and to contain Thread name:

public void run() {
    int counter=0;
    while (true) {

        try {
            String token = Thread.currentThread().toString() + "#"+(counter++);
            this.blockingQueue.put(token );
            System.out.println("Producer produced nr: " + token );
        } catch (InterruptedException e ) {
            System.out.println("Producer was interrupted");
        }
        sleep();
    }
}

Change Consumer.run() to print the thread name too, and you’ll see more clearly which Consumer instance is consuming each action and from which Producer:

System.out.println("consumer "+Thread.currentThread()+" gets: " + element);

This will hopefully demonstrate that these are several Producer + Consumer handlers and different permutations of Producer-Consumer sending and receiving items from the same BlockingQueue.