Skip to content
Advertisement

Problem with same thread ID for different threads

I am having trouble with my threads. I am trying to create 10 threads and for each thread I want to print the thread ID. I am able to print the thread ID but the problem is that all threads prints out the same thread ID.

This is my code:

main:

JavaScript

mqClient:

JavaScript

When testing two threads this is the output (observe the same thread ID):

JavaScript

The thread ID should be unique for each thread, so any idea why I am getting this kind of output?

Advertisement

Answer

In your loop in main you are creating 10 threads, but you don’t create them in parallel. You are creating one thread at a time, waiting for it to end, and only then proceeding with the loop. So you only create 0-1 threads at a time, but not 0-10 threads.

In general: two threads that exist at the same time have different IDs, but two threads that exist at different points in time can have the same ID.

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