import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CPUMonitor {
private static final Logger log=LoggerFactory.getLogger(CPUMonitor.class);
private static CPUMonitor instance = new CPUMonitor();
private ExecutorService workpool;
private int cpuIdleThreshold; //cpu空闲阈值
private int cpus; //cpu核数
private CPUMonitor() {
cpus = Runtime.getRuntime().availableProcessors();
workpool = Executors.newFixedThreadPool(cpus);
cpuIdleThreshold = 35;
}
public static CPUMonitor getInstance() {
return instance;
}
public int getProcessCpu() {
Runtime rt = Runtime.getRuntime();
String[] cmd = { "/bin/sh", "-c", "top -b -d 0.1 -n 2 | grep '%Cpu(s)' | sed -n '$p' | awk '{print $8}'" };
BufferedReader in = null;
String str = "";
try{
Process p = rt.exec(cmd);
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
str = in.readLine();
}catch(Exception e){
log.error("Get cpu utilization error.",e);
}
return (int)Float.parseFloat(str);
}
public void work(){
for(int i=0; i<cpus; i++){
workpool.submit(new Runnable() {
@Override
public void run() {
long threadId = Thread.currentThread().getId();
while(true){
int idle = getProcessCpu();
if(idle > cpuIdleThreshold){
log.info(String.format("Thread-%s cpu idle:%s", threadId, idle));
List<Object> addList = new ArrayList<Object>();
String str = "abcdefghijklmnopqrstuvwxyz";
double var;
for(int j=0; j<10000000; j++){
addList.add(str);
addList.add(str);
addList.add(str);
addList.clear();
var = (double)j/3.3;
}
}else{
try {
log.info(String.format("Thread-%s sleep:100ms", threadId));
Thread.sleep(100);
}catch (Exception e){
log.error("Thread sleep error.",e);
}
}
}
}
});
}
workpool.shutdown();
try {
while(!workpool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS)){
log.info("Thread pool is not shutdown");
}
}catch (Exception e){
log.error("Thread pool awaitTermination error.",e);
}
log.info("Thread pool is shutdown");
}
public static void main(String[] args){
CPUMonitor cpuMonitor = CPUMonitor.getInstance();
log.info("Service start...");
cpuMonitor.work();
}
}