Java Threads

Associate
Joined
14 Apr 2003
Posts
1,101
Hi,

I have an application that sends numerous requests to a server. I want to speed this up by using threads. My current idea is move the code that is responsible for sending the request to a new 'Runnable' class and then have a loop to create and start this thread. Now my question is this:

What is the best way to create (and maintain) a number, say 5, threads at all times? That is, I want to have 5 threads running at all times until all requests have been sent. Should I just use a while loop with a nested if?

Code:
while(numSent < totalRequests)
{
   if(numThreads < maxThreads) // spare thread, create and run one.
   {
      MyThread t = new MyThread(<some variables>);
      t.start();
   }
}

MyThread is then responsible for increasing the numSent variable so the while loop eventually exits. This doesn't seem very efficient to me as the main loop will be running excessively, doing nothing, while it waits for the requests to finish.

I have been looking into the wait() and notify() methods but can't seem to figure out how to apply them in this context. This must be a common design pattern?

Cheers.
 
have a look at join, that should do the trick.

so basically you fire off the threads and wait for them to exit.

you may want to maintain an array of threads so you can cleanup if necessary. I think you can use destory to do this, but you'll have to look around.
 
Create 5 threads, and an list of requests to be processed. Then just have the threads take requests from the list when they finish the current request. If they run out of requests to process you can pause the thread with wait and wake them up again with notify when a request is received.
 
Thanks guys, it seems the thread pool pattern is indeed what I am looking for - I'll give it a shot.

EDIT: Actually a lot simpler than I thought:

Code:
ExecutorService execSvc = Executors.newFixedThreadPool( numThreads );
for(String f: files)
{
	RequestThread t = new RequestThread(<some parameters>);
	execSvc.execute(t);
}
 
Last edited:
Back
Top Bottom