题目描述:让用户来决定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);
}
}
8044

被折叠的 条评论
为什么被折叠?



