编程之美--1.1控制CPU曲线
控制CPU运行曲线一直在50%
public class MyCPU { public static void main(String[] args) { // TODO Auto-generated method stub int busyTime = 10; int idleTime = 10; long startTime; // while(true){ // for(int i = 0 ; i < 960000000 ; i++) // ; // try { // Thread.sleep(10); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } while(true){ startTime = System.currentTimeMillis(); while(System.currentTimeMillis()-startTime<busyTime) ; try { Thread.sleep(idleTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
CPU曲线为正弦曲线
public class SinCPU { public static void main(String[] args) { // TODO Auto-generated method stub double PI = 3.14159265; int interval = 300; int Count = 200; // 数组大小; double[] busyTime = new double[Count]; double[] idleTime = new double[Count]; int half = interval / 2; double radian = 0.0; for (int i = 0; i < Count; i++) { busyTime[i] = half + Math.sin(PI * radian) * half; idleTime[i] = interval-busyTime[i]; radian+=0.01;//每次+0.01,200次,正好到2,上面括号里就是2PI } long startTime; int j = 0; while (true) { j=j%Count; startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < busyTime[j]) ; try { Thread.sleep((int)idleTime[j]); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } j++; } } }

浙公网安备 33010602011771号