views:

94

answers:

3

Hi, I want to have a while loop that launches a thread on each loop,

I am using the following to launch the thread, do I need to have a unique identifier for each thread or becuase it is launching from different loops will it launch ok, or will it overwrite the previous launch as they are using the same identifier?

while(x<y){
Runnable r = new Rule1("neil", 2, 0);
new Thread(r).start();
x++;
}
+6  A: 

It will work fine.

Your threads do not have any identifiers at all.
The r variable is a normal (and temporary) variable; you are passing its value to the Thread constructor.

The runtime isn't even aware of the variable.

SLaks
SLaks is right in response to the question of each thread not having identifiers... They would be considered anonymous (i.e there is no reference to the thread that is within scope for you to access...). This means that every time you go through the loop you are unable to obtain a reference to the previous instance of thread.
edwardTheGreat
+4  A: 

It will launch multiple threads. The only "unique identifier" for the thread is the ID returned by Thread.getId(), and you don't get to assign that. Even the thread name doesn't need to be unique. In other words, there's no unique identifier which is being reused here.

Certainly the fact that you're assigning the Thread reference to the same variable on each iteration doesn't mean the threads will care in the slightest.

Jon Skeet
The thread ID is unique in Java
Aaron
@Aaron: Yes, of course - will update to clarify.
Jon Skeet
A: 

While you do not need to create a unique identifier for each thread (framework will take care of it) it is best practice if at all possible to name your threads in relation to what they are doing so that when you begin debugging via logs/jvisualvm you are aware of the threads purpose.

Aaron