• Post Reply Bookmark Topic Watch Topic
  • New Topic

Any way to create dynamic named instances of a thread class?  RSS feed

 
Brian Ouellette
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have an application where I need to create a dozen different thread's, and I was wondering if anyone knows of a way to do this in JAVA.

Here is what I'm looking to do:

Existing Lengthy Approach below, where FactCalc is my factor calculation class that performs the work in each thread:

FactCalc myCalc = new FactCalc();

FactCalc.MyRunnable fact1State = myCalc.new MyRunnable();
Thread fact1 = new Thread(fact1State);

FactCalc.MyRunnable fact2State = myCalc.new MyRunnable();
Thread fact2 = new Thread(fact2State);

.... and so on to
FactCalc.MyRunnable fact12State = myCalc.new MyRunnable();
Thread fact12 = new Thread(fact12State);


Desired Approach:

I would like to use a variable to form the constructor names (shown in red) for 12 instances as the non-working snippet illustrates below.


for(int i=1; i<13; i++) {

FactCalc.MyRunnable fact(valueOf(i))State = myCalc.new MyRunnable();
Thread fact(valueOf(i)) = new Thread(fact(valueOf(i))State);

fact(valueOf(i)) .start(); // or Start may be done in another step/loop

} // end for loop


I'm not sure if this is possible in JAVA or not and looking for some feedback.

Thanks





 
Rodion Gork
Ranch Hand
Posts: 47
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
May be I've failed to understand you properly, but why not create an array of threads?



If you really want textual names you can use Map<String, Thread> instead of array, but as you want to index them with numbers, I believe you prefer array.
 
Brian Ouellette
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thank you very much, I was buried in the bowels and missed the most obvious solution. I just tried an array as you suggested and it works fine.

Thanks again!
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What about a cached thread pool?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!