0

I have a many calculations to do. All could run parallel... if there where no limit of RAM. :/

Because of that i want to control the number of threads working parallel.

I wrote the following code:

List<Thread> threadList = new ArrayList<Thread>();              
threadList.add(new Thread(new Runnable() {              
  @Override
  public void run() {
    ....
  }
}));            
threadList.get(threadList.size()-1).start();            
if(threadList.size() >= 5){                 
  threadList.remove(0).join();                  
}

With 1 this works fine as if there where no multithreading. But if i allow 2 it gets really crazy and the RAM is getting filled up.

Am i doing something wrong?

Spenhouet
  • 6,556
  • 12
  • 51
  • 76

1 Answers1

3

Please do not try to create your own Thread-List. Use existing Methods and common ways doing this.

One proper way is using a ThreadPoolExecutor. Check this for that. MultiThreading Vs ThreadPoolExecutor

You should also use an Executor which let you limit the number of Threads used in parallel/max. Example:

ExecutorService executor = Executors.newFixedThreadPool(10); 
executor.submit(yourfirstthread);
executor.submit(secondthread);
// and so on..
Community
  • 1
  • 1
Emanuel
  • 8,027
  • 2
  • 37
  • 56