WPE|52wpe|我爱WPE

 找回密码
 注册会员
搜索
  • 1719查看
  • 1回复

[经验分享] JAVA控制CPU的使用率

主题

好友

1172

积分

禁止发言

发表于 2009-7-1 16:25:54 |显示全部楼层
 JAVA代码,里面的循环和休眠时间,请根据你的机器情况修改,我的大致能稳定在43-44%之间。

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

  Java代码

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



  下面的代码可以控制比例

  Java代码

/**  
 * 编程之美,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代码

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

主题

好友

22

积分

新手上路

发表于 2009-7-8 12:08:11 |显示全部楼层
看不懂这什么?
回复

使用道具 举报

快速发帖

您需要登录后才可以回帖 登录 | 注册会员

手机版|Archiver|WPE|52wpe|我爱WPE ( 闽ICP备15009081号 )

GMT+8, 2024-5-21 08:32 , Processed in 0.064463 second(s), 16 queries .

返回顶部