66118833 发表于 2009-6-24 13:07:22

JAVA控制CPU的使用率

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;   
    long[] idleSpan = new long;   
    int half = INTERVAL / 2;   
    double radian = 0.0;   
    for (int i = 0; i < COUNT; i++) {   

中天 发表于 2010-1-31 01:12:48

我要灌水!!!!!!!!
页: [1]
查看完整版本: JAVA控制CPU的使用率