JAVA多线程设置优先级与CPU核数是否有关系

学习java基础多线程优先级时,发现按照教程的写法,无论如何设置优先级,低优先级的线程占用的CPU时间并不比高优先级的长多少。

package practice;

public class HiLoPri {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
		clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
		clicker lo = new clicker(Thread.NORM_PRIORITY);
		lo.start();
		hi.start();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			System.out.println("Main thread interrupted");
		}
		lo.stop();
		hi.stop();
		try {
			hi.t.join();
			lo.t.join();
		} catch (InterruptedException e) {
			System.out.println("InterruptedException caught");
		}

		System.out.println("Low-priority thread:" + lo.click);
		System.out.println("High-priority thread:" + hi.click);
	}

}

class clicker implements Runnable {
	long click = 0;
	Thread t;
	private volatile boolean running = true;

	public clicker(int p) {
		t = new Thread(this);
		t.setPriority(p);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (running) {
			click++;
		}
	}

	public void stop() {
		running = false;
	}

	public void start() {
		t.start();
	}

}

执行结果

Low-priority thread:3621884808
High-priority thread:3641550389

可以看到并不高多少,于是尝试修改优先级大小等级

clicker hi = new clicker(Thread.NORM_PRIORITY + 4);
clicker lo = new clicker(Thread.NORM_PRIORITY - 4);

执行结果

Low-priority thread:3362383480
High-priority thread:3680814061

一样并未差多少,于是我想到应该是我的电脑CPU核数大于2线程的缘故,于是增加线程

clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY);
clicker lo1 = new clicker(Thread.NORM_PRIORITY - 1);
clicker lo2 = new clicker(Thread.NORM_PRIORITY - 2);
clicker lo3 = new clicker(Thread.NORM_PRIORITY - 3);
clicker lo4 = new clicker(Thread.NORM_PRIORITY - 4);

执行结果

Low-priority thread:3492617737
Low1-priority thread:1371754450
Low2-priority thread:1371994714
Low3-priority thread:46415409
Low4-priority thread:46436207
High-priority thread:3626637091

明显其后的低优先级线程占用时间有了明显的缩短,因此设置优先级线程占用的CPU时间与当前终端的CPU核心数有一定的关系

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值