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

来源:互联网 发布:java程序结构 编辑:程序博客网 时间:2024/04/28 01:52


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

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

  1. public class T {
  2.   public static void main(String[] args) throws Exception {
  3.     for (;;) {
  4.       for (int i = 0; i < 96000000; i++)
  5.         ;
  6.       Thread.sleep(10);
  7.     }
  8.   }
  9. }


运行效果


下面的代码可以控制比例

  1. /**
  2.  * 编程之美,JAVA控制CPU的使用率(2),精确控制比例。
  3.  * 
  4.  * @author 赵学庆,Java世纪网(java2000.net)
  5.  * 
  6.  */
  7. public class T {
  8.   static int busyTime = 10;
  9.   static int idelTime = busyTime; // 50%的占有率
  10.   public static void main(String[] args) throws Exception {
  11.     long startTime = 0;
  12.     while (true) {
  13.       startTime = System.currentTimeMillis();
  14.       while (System.currentTimeMillis() - startTime < busyTime)
  15.         ;
  16.       Thread.sleep(idelTime);
  17.     }
  18.   }
  19. }

下一个文章我将实现那个完美曲线。

今天先去上班了,晚上回来再写。呵呵!

提示:
编程之美,JAVA控制CPU的使用率(2),完美曲线 已经完成


原创粉丝点击