lmsasu
lmsasu

Reputation: 7583

Running at most n Java threads

I have a CPU intensive application, which can be written in Java. The application consists of few jobs (threads) that run independently.

If I start all the threads at once, the system will be overloaded. How could I start at most n threads at once, and when one thread finishes then a new one is started? By limiting the number of threads running at once, I intend to leave some other processors/cores available for other tasks.

Thanks

Upvotes: 2

Views: 525

Answers (2)

Mike Daniels
Mike Daniels

Reputation: 8642

You should formulate your threads' tasks as Runnables or Callables and then submit them to a fixed thread pool executor. The executor will manage a pool of worker threads and run your tasks from an internal queue on those threads.

See Executors#newFixedThreadPool for a factory method that creates the type of executor you want.

Upvotes: 15

Peter Lawrey
Peter Lawrey

Reputation: 533492

Use a fixed size executor pool.

 ExecutorService executor = Executors.newFixedThreadPool(4);

Upvotes: 7

Related Questions