java 优化线程,100%CPU使用率的Java线程优化

本文探讨了在Java应用程序中处理大量并发计算密集型任务时,如何优化线程池大小以避免CPU达到100%。作者考虑是否应该根据CPU使用情况动态调整线程数量,或者让Java的线程调度器自动处理。内容指出,当线程数量超过处理器核心数时,会增加上下文切换的开销。同时,由于任务复杂性和I/O操作,保持CPU在一定阈值以下是更优选择。
摘要由CSDN通过智能技术生成

I have an application that accepts work on a queue and then spins that work off to be completed on independent threads. The number of threads is not massive, say up to 100, but these are intensive tasks and can quickly bump the CPU up to 100%.

To get the most work done the quickest: am I best off to just launch more threads when I need to do more work and let the Java thread scheduler handle distributing the work, or would getting smarter and managing the work load to keep the CPU below 100% get me further faster?

The machine is dedicated to my java app.

EDIT:

Thanks for the fantastic input!

The tasks are of varying complexity and involve I/O so having a low thread pool of say 4 may well be only running the CPU to 20%. I have no way of knowing how many tasks will actually take the CPU to 100%.

My thought was should I monitor CPU through RMI and dynamically dial the work up and down, or should I just not care and let the OS handle it.

解决方案

If you have too many simultaneous compute-intensive tasks in parallel threads, you reach the point of diminishing returns very quickly. In fact, if there are N processors (cores), then you don't want more than N such threads. Now, if the tasks occasionally pause for I/O or user interaction, then the right number can be somewhat larger. But in general, if at any one moment there are more threads that want to do computation than there are cores available, then your program is wasting time on context switches -- i.e., the scheduling is costing you.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值