Skip to content
Advertisement

Why initialValue of ThreadLocal doesn’t increment my variables?

I am learning about multithreading; and I have the following ThreadID class:

JavaScript

and the following Thread class:

JavaScript

and my main Class:

JavaScript

Question:

What I want is to give each Thread an ID; I found that when I init the id in the thread constructor the value is always 0 (normally the initialValue should increment the nextID)

JavaScript

but when I init the id inside the Run function it works !

JavaScript

Can any one explain why this happens?

Advertisement

Answer

What I want is to give each Thread an ID I found that when I init the id in the thread constructor the value is always 0 (normally the initialValue should increment the nextID)

So in the MyThread1 class constructor you do:

JavaScript

In this case, the thread actually calling tID.get(); is the main thread, i.e., the thread that is calling those constructors, from the main class:

JavaScript

The first call to tID.get() will generate a new ID as 0, since it is the first time that any thread is calling tID.get(). The next calls from the same thread (i.e., main thread) will not generate a new ID, but instead, it always returns the same ID, in this case, return 0 for the main thread.

but when I init the id inside the Run function it works!

Inside the run method:

JavaScript

the tID.get() will be called by different threads, and that is why you get new IDs. One new ID per thread calling for the first time tID.get().

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