您的位置:首页 > 编程语言 > Java开发

压力测试时,利用Java让CPU使用率达到100%

2013-10-01 21:14 519 查看
如果你还没达到100%,增加下面的for循环次数。

import java.io.IOException;

public class CPUTest {
	public static void main(String[] args) {
		
		CPUTestThread cpuTestThread = new CPUTestThread();
		for (int i = 0; i < 3; i++) {
			Thread cpuTest = new Thread(cpuTestThread);
			cpuTest.start();
		}
		
		//Windows Task Manager shows
		try {
			Runtime.getRuntime().exec("taskmgr");
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}

class CPUTestThread implements Runnable {

	@Override
	public void run() {
		int busyTime = 10;
		int idleTime = busyTime;
		long startTime = 0;
		while (true) {
			startTime = System.currentTimeMillis();
			System.out.println(System.currentTimeMillis()+","+startTime+","+(System.currentTimeMillis() - startTime));

			// busy loop
			while ((System.currentTimeMillis() - startTime) <= busyTime)
				;
			// idle loop
			try {
				Thread.sleep(idleTime);
			} catch (InterruptedException e) {
				System.out.println(e);
			}
		}

	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: