Skip to content
Advertisement

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:

JavaScript

output: but it doesn’t work because the threads are overlapping each other

JavaScript

Advertisement

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:

JavaScript

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:

JavaScript

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement