When I try to learn about Java threads, I usually come across with the code examples with wait() and notify() in the very same class (infact nearly all of them producer-consumer examples). After googling various examples, unfortunately I could not find the the case I need which is:
- A manager thread initially creates n number of threads (and starts them) in which a http get request is done in a sigle thread.
- For a single worker thread it takes about 20-30 seconds to complete its life.
- Here my manager thread must know which of workers have finished, and replaces finishing thread with a new one.
I thought about an approach like that (let n be 5):
List<Runnable> runnables = new ArrayList<Runnable>();
for(int i = 0 ; i < 5 ; i++){
runnables.add(new MyWorker(params));
}
for(Runnable myWorker : runnables){
myWorker.run();
}
Since wait() does not support multiple objects I cannot keep on going from here. Another solution can be implementing busy wait on manager thread that is calling some isFinished flag for each worker. But I’m not sure either this a good approach (as far as I know this is resource wasting)
There is a ready-to-use tool in Java 6 and above, in the form of the executor framework.
Since you want to have a fixed pool of threads, your best bet is to use:
You can then submit your
Runnableinstances using the.execute()method (which is defined by theExecutorinterface). They will be submitted to a work queue and dequeued as soon as a thread in the pool is available.If your individual thread-working methods return a value (ie, they implement
Callable<Something>), then you can use the.submit()method (defined byExecutorService, also an interface which extendsExecutor), which will return aFuture<Something>from which you will.get()the computed values.Terminating a thread pool is done in various ways:
.shutdown()is the most basic and will synchronously wait for still active threads to terminate (and prevent new jobs to be submitted).Javadocs: Executors, ExecutorService, ThreadPoolExecutor.
Other link: a book you should buy for all things thread-related (does not cover Java 7’s
ForkJoinPoolhowever).PS: how lucky, the sample chapter of the book above (PDF) covers task execution 😉