开发者

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


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.


Use a fixed size executor pool.

 ExecutorService executor = Executors.newFixedThreadPool(4);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜