前言
遇到了这样一个问题:客户要求服务器的cpu要达到一定的使用率
分析
占用cpu的情况我这边想到的是使用java程序包运行起来占着线程就可以了
占用内存的情况就不用说了上传几个大文件就行了
解决办法
1.代码
我这里使用的springboot项目,打算后边把项目打成jar在服务器上运行的占用cpu
想法是:实现多线程运行一个死循环
// 实现线程类
public class CpuTest implements Runnable{
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
int busyTime = 10;
int idleTime = busyTime;
/*while(true)是一个无穷循环语句*/
while (true) {
/*总毫秒数 从1970年1月1日开始计算*/
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) <= busyTime);
try {
/*线程睡眠 时间单位为 毫秒/ms 1s=1000ms*/
Thread.sleep(idleTime);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName()+"===================>"+startTime);
}
}
}
// 创建运行线程
@SpringBootApplication
public class CpuDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CpuDemoApplication.class, args);
CpuTest test = new CpuTest();
// 可以调整线程多少来处理占用cpu的情况
new Thread(test,"A线程一运行").start();
new Thread(test,"B线程二运行").start();
new Thread(test,"C线程三运行").start();
new Thread(test,"D线程四运行").start();
new Thread(test,"E线程五运行").start();
}
}
2.实操
上传打包好的jar包运行在做调试,查看占用cpu情况
[admin@i-CB12345 ~]$ cd /home/app/ # 进入放jar的目录
# 这里考虑到是个死循环如果日志都输出的话日志文件会很大
# 所以只输出错误信息到日志文件,标准输出不写入日志文件,直接丢弃,运行如下
[admin@i-CB12345 ~]$ nohup java -jar cpu-occupy.jar >/dev/null 2>log.error &
[1] 17923
[admin@i-CB12345 ~]$ ll
total 9492
-rw-r--r-- 1 gzgsczy root 8867412 Apr 12 15:06 cpu-occupy.jar
-rw-r--r-- 1 gzgsczy root 839547 Apr 12 15:14 log.error
总结
服务器占用cpu这种情况,不同的服务器性能不同,多占一点线程肯定是可以占用cpu的使用率的