Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to only run a few threads at a time...

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you want is a thread pool. Do some searching and you should find some answers.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In JDK 5 look at Executors for a starting point. The newXXXThreadPool methods give you pools designed to do exactly what you need.
 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will search around, but I am not able to use jdk 1.5 at this time.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic