Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable Thread Number

 
Davide Crudo
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Experts,

Is there a way to have a method generate a certain amount of threads to do the job?

Normally i would manually create each single thread and start it, but what if i want the user to choose
how many threads to use without pre building them for various cases?

for instance something like this (where "t&i" is a dynamic variable name):



I could accomplish the above, with the following, but i was thinking if there is a shorter way:
(the code below is taking the advantage that the variable dies with the block, but the thread still
carries the job to the end before killing the variable. In any case, once the thread is dead, is dead,
so this code would then dispose of the "t" variable with the next garbage collection...




Thanks!
Dave

 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no need to introduce a variable if you don't want one - "new Thread(nw).start()" works fine. If you're worrying about the overhead of allocating and disposing "t", that's highly unlikely to be measurable, much less noticeable by a human being.

By the way, "for (int i=0; i < numberOfThreadsWanted-1; i++)" only creates "numberOfThreadsWanted-1" threads - which may be one less than desired.
 
Davide Crudo
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ulf!

You have an eagle eye to spot the issue with the loop variable! I always miss those...i eventually found it while debugging that running with one thread did not work...

... I always forget about the single notation with parameter passing...

I'm playing for the first time with threads..;)

Thanks for the great and quick help!

Dave
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic