如何验证JAVA Thread sleep是否会占用CPU资源
关于 sleep 是否会放弃CPU资源的小实验:
为了效果明显,对多个线程同时操作
① 创建多个线程,使它们同时执行 sleep 方法 ,查看程序的线程数以及CPU
第一次执行代码如下:
@Test
public void ThreadTest() throws InterruptedException {
for(int i = 0; i < 40; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("开启线程名称 :"+Thread.currentThread().getName());
try {
Thread.sleep(30*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
}
System.out.println("主线程名称:"+Thread.currentThread().getName());
long start = System.currentTimeMillis();
long end = start;
long time = start - end;
while(time < 40*1000 ) {
end = System.currentTimeMillis();
time = end -start;
}
}
结果如下: sleep 后 CPU 使用情况并不高,程序中的线程确实是存在的
② 创建和第一次实验一样多的线程,只使其中一半线程 sleep ,另一半处于运行状态:
实验代码如下:
@Test
public void ThreadTest() throws InterruptedException {
for(int i = 0; i < 20; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("开启线程名称 :"+Thread.currentThread().getName());
try {
Thread.sleep(30*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
}
for(int i = 0; i < 20; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("开启线程名称 :"+Thread.currentThread().getName());
try {
long start = System.currentTimeMillis();
long end = start;
long time = end - start;
while(time < 30*1000 ) {
end = System.currentTimeMillis();
time = end -start;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
}
System.out.println("主线程名称:"+Thread.currentThread().getName());
long start = System.currentTimeMillis();
long end = start;
long time = start - end;
while(time < 40*1000 ) {
end = System.currentTimeMillis();
time = end -start;
}
}
第二次实验结果如下: 可以看到 CPU 在一定区间内上升到 100%,
问题分析:
第一次 | 第二次 | |
---|---|---|
CPU使用情况 | 基本稳定在 12% | 运行程序后CPU迅速飙升 |
开启线程数量 | 40个线程全都调用sleep方法 | 40个线程(20个线程调用sleep方法,20个线程在30秒内空轮询占用 CPU资源) |
参考: https://blog.csdn.net/weixin_41960204/article/details/106785986