编程之美-JAVA控制CPU的使用率

 

 

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);
     }
   }
 }

 

 

下面的代码可以控制比例

 /**
  * 编程之美,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++;
    }
  }
}
 

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值