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)
ThreadPoolExecutor. See also utility classExecutors, which has static factory methods for the most common scenarios.