File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Variable Thread Number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Variable Thread Number" Watch "Variable Thread Number" New topic

Variable Thread Number

Davide Crudo
Ranch Hand

Joined: Sep 08, 2009
Posts: 62
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...


Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42959
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

Joined: Sep 08, 2009
Posts: 62
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!

I agree. Here's the link:
subject: Variable Thread Number
jQuery in Action, 3rd edition