---
title: "让CPU占用率划出一条直线（Java实现）"
author: "walsh"
date: "2009-08-13T10:31:34Z"
tags: []
categories: ["编程语言"]
slug: "cpu-java"
draft: false
lastmod: "2009-08-13T10:31:34Z"
id: 446136
url: "https://walsh.iteye.com/blog/446136"
---

<span style="color:red">**CPU占用率**</span>：在任务管理器的一个刷新周期内，CPU忙（执行应用程序）的时间和刷新周期总时间的比率，就是CPU的占用率。
    那么如何让CPU占用率曲线听自己指挥呢？以50%为例，用Java代码实现。

```java
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);
			}
		}
	}
}
```


运行结果如下：

![](/upload/attachment/135361/f8d83bd7-e868-3d05-afe8-20fb5265cb1f.png)