[英]Running at most n Java threads
I have a CPU intensive application, which can be written in Java. 我有一个CPU密集型应用程序,可以用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?
我怎么能一次启动最多n个线程,当一个线程完成然后启动一个新线程? 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 Runnable
s or Callable
s and then submit them to a fixed thread pool executor. 您应该将线程的任务表示为
Runnable
或Callable
,然后将它们提交给固定的线程池执行程序。 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. 请参阅Executors#newFixedThreadPool以获取创建所需执行程序类型的工厂方法。
使用固定大小的执行程序池。
ExecutorService executor = Executors.newFixedThreadPool(4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.