---
title: "转：怎样让cpu的使用率为一条直线 （Java实现）"
author: "Ivan0513"
date: "2014-01-20T10:02:31Z"
tags: []
slug: "cpu-java"
draft: false
lastmod: "2014-01-20T10:02:31Z"
id: 2007207
url: "https://ivan0513.iteye.com/blog/2007207"
---

原文链接：[http://www.iteye.com/problems/24993](http://www.iteye.com/problems/24993)

 

最近在一本叫编程之美的书上看到这样一个问题，怎样使你的cpu的使用成为一条直线。书上的代码是这样的  
需要cpu的时钟频率 且计算机执行代码是平均每个时钟频率执行两行代码  
结果 如果是一个主频为 2.4Ghz的cpu  
那么 循环次数是 2.4\*1000 000 000 \*2/5 = 96 000 000  
对于计算机的休眠，如果sleep（1000）（即休眠1秒）效果不是很明显，减少一个数量级，即sleep（10），

 

```
int main(){
   
    for(;;){
       for(int i=0;i<960000;i++){
             ;
             sleep(10);
       }
    return 0;
   }
```

 

上面的代码是简写式的，可能有语法错误，希望高手给说说如何用java语言控制cpu的使用率为一条直线

如果是双cpu呢 怎么控制用一个cpu来执行程序，还有我试过了，没有达到书上说的要求。

刚才在网上搜了下，找到答案了，共同学习下

```
public class CPUTest {   
		public static void main(String[] args) {    
		int busyTime = 10;    
		int idleTime = busyTime;    
		long startTime = 0;    
		while (true) {     
			startTime = System.currentTimeMillis();     // busy loop
		while ((System.currentTimeMillis() - startTime) <= busyTime)      ;     // idle
																				// loop
			try {      
				Thread.sleep(idleTime);     
				} 
			catch (InterruptedException e) {      
				System.out.println(e);     
				}    
		}  
	}
```