编程之美一 : 让CPU占有率曲线听你指挥

来源:互联网 发布:网络会员管理系统 编辑:程序博客网 时间:2024/05/19 06:36

写一个程序,让用户来决定Windows任务管理器(Task Manager)的CPU占有率。程序越精简越好,可以实现以下三种情况:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /**** 
  2.  *  
  3.  * 1. JAVA控制CPU的占有率 - 固定在50%,为一条直线 
  4.  *  
  5.  ****/  
  6. public class CPUTest1 {  
  7.     public static void main(String[] args) throws Exception{  
  8.         for (;;) {  
  9.             for (int i = 0; i < 96000000; i++) {  
  10.                 ;  
  11.             }  
  12.             Thread.sleep(10);  
  13.         }  
  14.     }  
  15. }  

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /**** 
  2.  *  
  3.  * 2. JAVA控制CPU的占有率 - 控制在50% 
  4.  *  
  5.  ****/  
  6. public class CPUTest2 {  
  7.     static int busyTime = 10;  
  8.     static int idelTime = busyTime; // 50%的占有率  
  9.   
  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.             }  
  17.             Thread.sleep(idelTime);  
  18.         }  
  19.     }  
  20. }  

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. /**** 
  2.  * 3. JAVA控制CPU的使用率 - 完美曲线 
  3.  *  
  4.  * 把一条正弦曲线0~2π之间的弧度等分成200份进行抽样,计算每个抽样点的数据  
  5.  * 然后每隔300ms的时间取下一个抽样点,并让cpu工作对应振幅的时间 
  6.  *  
  7.  ****/  
  8. public class CPUTest3 {  
  9.     public static final int SAMPLING_COUNT = 200// 抽样点数量 2/RANDIAN_INCREMENT  
  10.     public static final double PI = Math.PI; // pi值  
  11.     public static final double RANDIAN_INCREMENT = 0.01// 抽样弧度的增量, 2/SAMPLING_COUNT  
  12.     public static final int TOTAL_AMPLITUDE = 300// 振幅, 每个抽样点对应的时间片  
  13.   
  14.     public static void main(String[] args) throws Exception {//  角度的分割     
  15.         long[] busySpan = new long[SAMPLING_COUNT];  
  16.         long[] idleSpan = new long[SAMPLING_COUNT];  
  17.         int amplitude = TOTAL_AMPLITUDE / 2;  
  18.         double radian = 0.0;  
  19.         for (int i = 0; i < SAMPLING_COUNT; i++) {  
  20.             busySpan[i] = (long) (amplitude + (Math.sin(PI * radian) * amplitude));  
  21.             radian += RANDIAN_INCREMENT;  
  22.         }  
  23.         long startTime = 0;  
  24.         for (int j = 0;; j = (j + 1) % SAMPLING_COUNT) {  
  25.             startTime = System.currentTimeMillis();  
  26.             while (System.currentTimeMillis() - startTime < busySpan[j]) {  
  27.                 ;  
  28.             }  
  29.             Thread.sleep(idleSpan[j]);  
  30.         }  
  31.     }  
  32. }  
1 0
原创粉丝点击