文章目录
本文档只是为了留档方便以后工作运维,或者给同事分享文档内容比较简陋命令也不是特别全,不适合小白观看,如有不懂可以私信,上班期间都是在得
原由,某申请得服务器,说我扫描到我服务器说长期cpu占用率过低要收回,特意搞了个demo来占用cpu,直接上代码了
上demo前
package com.joxp.cpu;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Component
public class CpuMemoryHogController {
private static volatile boolean running = false;
private static final List<byte[]> memoryHogList = new ArrayList<>();
private static final ExecutorService executorService = Executors.newCachedThreadPool();
@PostConstruct
public String startHog() {
if (running) {
return "Hog is already running!";
}
running = true;
// 启动 CPU 占用线程
int cpuCount = Runtime.getRuntime().availableProcessors();
for (int i = 0; i < cpuCount; i++) {
executorService.submit(this::cpuHog);
}
// 动态计算并增加内存占用
hogMemoryTo70Percent();
return "CPU and memory hogging has started!";
}
/**
* cpu占用百分之80
*/
private void cpuHog() {
while (running) {
// 进行计算,以便持续占用 CPU
for (int i = 0; i < 1000000; i++) {
// 将结果赋值给变量,避免“Not a statement”错误
double result = Math.sin(i) * Math.cos(i);
}
// 适当休眠以降低 CPU 使用率
try {
// 休眠时间可以根据需要调整
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/**
* 将内存提高到70%
*/
private void hogMemoryTo70Percent() {
// 获取当前可用内存和总内存
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long targetMemoryUsage = (long) (maxMemory * 0.7);
long usedMemory = runtime.totalMemory() - runtime.freeMemory();
long memoryToAllocate = targetMemoryUsage - usedMemory;
// 分配内存
while (memoryToAllocate > 0) {
int allocationSize = Math.min(1024 * 1024, (int) memoryToAllocate);
byte[] memoryHog = new byte[allocationSize];
memoryHogList.add(memoryHog);
memoryToAllocate -= allocationSize;
// 适当休眠以避免瞬时内存分配高峰
try {
// 可以根据需要调整这个休眠时间
Thread.sleep(5);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// 强制进行垃圾回收(仅供参考)
System.gc();
}
@GetMapping("/stop")
public String stopHog() {
running = false;
// 关闭线程池并清理内存
executorService.shutdownNow();
memoryHogList.clear();
return "Hogging has been stopped!";
}
}
启完服务
如果点赞多,评论多会更新详细教程,待补充。