龙空技术网

让CPU占用率曲线呈现一条直线

编程之美007 144

前言:

眼前看官们对“java画线条函数”大约比较关切,朋友们都需要学习一些“java画线条函数”的相关资讯。那么小编在网上汇集了一些对于“java画线条函数””的相关知识,希望我们能喜欢,各位老铁们快快来了解一下吧!

一、题目

让cpu的占用率固定在50%,为一条直线

二、思路

1、cpu占用率=非空闲进程占用时间/cpu总的运行时间

2、cpu总的运行时间=空闲时间+非空闲时间

3、让cpu busy time==cpu sleep time

三、java code

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Main { public static void main(String[] args) {Runtime r = Runtime.getRuntime(); //获得当前系统的CPU数量,根据这个数值创建对 数量的线程 ExecutorService pool = Executors.newFixedThreadPool( r.availableProcessors()); for (int i = 0; i < r.availableProcessors(); i++) { pool.execute(new cpuControl()); } pool.shutdown(); }}public class cpuControl implements Runnable {@Override public void run() {int busyTime = 50;//可调节参数,单位为ms。50ms后线程休眠50毫秒,然后再经系统调度 //。该数值越小,则线程被调度得越频繁,则CPU使用率也就越高(平均) int idleTime = busyTime; while (true) { long startTime = System.currentTimeMillis(); //busy loop: while ((System.currentTimeMillis() - startTime) <= busyTime) ; try { Thread.sleep(idleTime); } catch (InterruptedException e) { e.printStackTrace(); } } }}

四、运行效果图

标签: #java画线条函数