开发者

Launching threads from within while loop, what happens?

开发者 https://www.devze.com 2023-01-21 07:22 出处:网络
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 d

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<开发者_C百科;y){
Runnable r = new Rule1("neil", 2, 0);
new Thread(r).start();
x++;
}


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消