I frequently receive OUT of Memory errors. I expect this...
My country arrayLis listed below has a size of over 200. I only want to run maye 10 threads at a time... How do I do this? I know I can make my loop 10, but I would not know when the first 10 were done to run the next 10.
for(int i = 0; i!= countries.size(); i++){
Person who = new Person(); who.country = (String)countries.get(i); Thread t = new Thread(who); t.start(); }
Steven Bell
Ranch Hand
Joined: Dec 29, 2004
Posts: 1071
posted
0
What you want is a thread pool. Do some searching and you should find some answers.
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
0
In JDK 5 look at Executors for a starting point. The newXXXThreadPool methods give you pools designed to do exactly what you need.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Anthony Smith
Ranch Hand
Joined: Sep 10, 2001
Posts: 285
posted
0
I will search around, but I am not able to use jdk 1.5 at this time.
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
0
For older JREs, Google for Doug Lea's Concurrency package or the Apache Commons thread pool. Doug Lea's code was the foundation for most of the stuff in JDK5 but I found the final Sun version much easier to get started with. I thought the Apache Commons code was very readable and surprisingly simple.
The central trick is a blocking queue of tasks to run. You make a Runnable and put it in the queue instead of starting it on a thread. Some number of executor threads pull tasks from the queue and call the run() method. If the queue goes empty the executors block, waiting for new commands. If all the threads are busy tasks pile up in the queue for a while. Much simpler than you might expect.