轻松操控cpu曲线

题目描述:让用户来决定windows 任务管理器的cpu占用率

1.cpu的固定占用率50%,为一条直线

2.cpu占用率为一条直线,具体占用率由命令行参数决定;

3.cpu占用率为一条正弦曲线;


//看了编程之美,本来感觉这道题挺难做的。上面说的让我感觉自己不可能做出来,本来想直接到网上搜答案了,可是心有不甘,打算挑战下自己。

迫使自己静下心来想了一下!!

首先要知道任务管理器那条cpu曲线是怎么计算的。上网一查,程序也就出来了!!20分钟不到搞定前两问。

windows 任务管理器每1s钟刷新一次,所以在这一秒钟之内让cpu运行多少毫秒就占用百分之多少了。

说明:本机为双核的,所以开两个线程;

public class TestCpu implements Runnable{


private static long mills;
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
long old = System.currentTimeMillis();
while(System.currentTimeMillis()-old<=mills)
{
continue;
}
try {
Thread.sleep(1000-mills);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public static void occupy(int percent)
{
mills = percent*10;
TestCpu cpu = new TestCpu();
Thread test = new Thread(cpu);
Thread test1 = new Thread(cpu);
test.start();
test1.start();
}
public static void main(String[] args)
{
TestCpu.occupy(30);
}


}

正弦曲线显示:



public class TestCpu implements Runnable{


private static long mills;
@Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
while(true)
{
i = i+10;

mills = (int)(Math.sin(i*Math.PI/181)*1000);

mills = mills/2 + 500;

System.out.println(mills);
long old = System.currentTimeMillis();
while(System.currentTimeMillis()-old<=mills)
{
continue;
}
try {
Thread.sleep(1000-mills);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public static void occupy(int percent)
{
//mills = percent*10;
TestCpu cpu = new TestCpu();
Thread test = new Thread(cpu);
Thread test1 = new Thread(cpu);
test.start();
test1.start();
}
public static void main(String[] args)
{
//System.out.println((int)(Math.sin(80*3.14/181)*100));
TestCpu.occupy(1);
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值