《编程之美》当中的引子。
如何编程实现控制CPU的使用率维持在50%?
直接分为busy和idle时间。
因为是取平均值,所以两者各占一半,即可实现50%。
笨方法:
public static void main(String args[]) throws InterruptedException{
for(;;){
for(int i=0;i<30760000;i++)
;
Thread.sleep(10);
}
}
其中i做循环的次数,取决于计算机的不同。
图一:
好方法:
使用System.currentTimeMillis()
public static void main(String args[]) throws InterruptedException{
int busyTime = 10;
int idleTime = busyTime;
while(true){
long startTime = System.currentTimeMillis();
//busy loop:
while((System.currentTimeMillis()-startTime)<=busyTim