---
title: "编程之美-JAVA控制CPU的使用率"
author: "java2000.net"
date: "2008-10-26T15:29:18Z"
tags: []
slug: "java-cpu"
draft: false
lastmod: "2008-10-26T15:29:18Z"
id: 258168
url: "https://java2000-net.iteye.com/blog/258168"
---

JAVA代码，里面的循环和休眠时间，请根据你的机器情况修改，我的大致能稳定在43-44%之间。

这个是粗的代码，后面我会继续完善，实现那个完美曲线。

 

```
public class T {

   public static void main(String[] args) throws Exception {
     for (;;) {
      for (int i = 0; i < 96000000; i++)
         ;
      Thread.sleep(10);
     }
   }
 }
```

 ![](http://p.blog.csdn.net/images/p_blog_csdn_net/java2000_net/EntryImages/20081024/2008-10-24_071807.gif)

 

下面的代码可以控制比例

```
 /**
  * 编程之美，JAVA控制CPU的使用率(2),精确控制比例。
  * 
  * @author 赵学庆，Java世纪网(java2000.net)
  * 
  */
 public class T {

   static int busyTime = 10;
   static int idelTime = busyTime; // 50%的占有率

   public static void main(String[] args) throws Exception {
     long startTime = 0;
    while (true) {
       startTime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startTime < busyTime)
         ;
       Thread.sleep(idelTime);
     }
   }
 }
```

 

 

下面的代码可以生成还算完美的正弦曲线

```
/**
 * 编程之美，JAVA控制CPU的使用率(2),完美曲线
 * 
 * @author 赵学庆，Java世纪网(java2000.net)
 * 
 */
public class T {

  public static void main(String[] args) throws Exception {
    // 角度的分割
    final double SPLIT = 0.01;
    //
    // 2PI分割的次数，也就是2/0.01个，正好是一周
    final int COUNT = (int) (2 / SPLIT);
    final double PI = Math.PI;
    // 时间间隔
    final int INTERVAL = 200;
    long[] busySpan = new long[COUNT];
    long[] idleSpan = new long[COUNT];
    int half = INTERVAL / 2;
    double radian = 0.0;
    for (int i = 0; i < COUNT; i++) {
      busySpan[i] = (long) (half + (Math.sin(PI * radian) * half));
      idleSpan[i] = INTERVAL - busySpan[i];
      radian += SPLIT;
    }
    long startTime = 0;
    int j = 0;
    while (true) {
      j = j % COUNT;
      startTime = System.currentTimeMillis();
      while (System.currentTimeMillis() - startTime < busySpan[j])
        ;
      Thread.sleep(idleSpan[j]);
      j++;
    }
  }
}
```

 

![](http://p.blog.csdn.net/images/p_blog_csdn_net/java2000_net/EntryImages/20081024/2008-10-24_104648.png)