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

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

/****
 * 
 * 1. JAVA控制CPU的占有率 - 固定在50%,为一条直线
 * 
 ****/
public class CPUTest1 {
	public static void main(String[] args) throws Exception{
		for (;;) {
			for (int i = 0; i < 96000000; i++) {
				;
			}
			Thread.sleep(10);
		}
	}
}

/****
 * 
 * 2. JAVA控制CPU的占有率 - 控制在50%
 * 
 ****/
public class CPUTest2 {
	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);
		}
	}
}

/****
 * 3. JAVA控制CPU的使用率 - 完美曲线
 * 
 * 把一条正弦曲线0~2π之间的弧度等分成200份进行抽样,计算每个抽样点的数据 
 * 然后每隔300ms的时间取下一个抽样点,并让cpu工作对应振幅的时间
 * 
 ****/
public class CPUTest3 {
	public static final int SAMPLING_COUNT = 200; // 抽样点数量 2/RANDIAN_INCREMENT
	public static final double PI = Math.PI; // pi值
	public static final double RANDIAN_INCREMENT = 0.01; // 抽样弧度的增量, 2/SAMPLING_COUNT
	public static final int TOTAL_AMPLITUDE = 300; // 振幅, 每个抽样点对应的时间片

	public static void main(String[] args) throws Exception {//  角度的分割   
		long[] busySpan = new long[SAMPLING_COUNT];
		long[] idleSpan = new long[SAMPLING_COUNT];
		int amplitude = TOTAL_AMPLITUDE / 2;
		double radian = 0.0;
		for (int i = 0; i < SAMPLING_COUNT; i++) {
			busySpan[i] = (long) (amplitude + (Math.sin(PI * radian) * amplitude));
			radian += RANDIAN_INCREMENT;
		}
		long startTime = 0;
		for (int j = 0;; j = (j + 1) % SAMPLING_COUNT) {
			startTime = System.currentTimeMillis();
			while (System.currentTimeMillis() - startTime < busySpan[j]) {
				;
			}
			Thread.sleep(idleSpan[j]);
		}
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值