【高并发系列】7、线程优先级

优先级高的线程在竞争资源时会更有优势,更可能抢占资源,只是一个概率问题;

线程的优先级调度和底层操作系统有密切的关系,在各个平台上表现不一,并且无法精准控制,因此在要求严格的场合,需要开发者在应用层解决线程调度问题;

线程优先级用内置3个静态标量表示:

/**
 * The minimum priority that a thread can have.
 */
public final static int MIN_PRIORITY = 1;
/**
 * The default priority that is assigned to a thread.
 */
public final static int NORM_PRIORITY = 5;
/**
 * The maximum priority that a thread can have.
 */
public final static int MAX_PRIORITY = 10;

虽然设置最高和最低优先级,但真正执行结果不可预测:

public class ThreadPriorityDemo {
	public static class HighPriorityThread extends Thread {
		static int count = 0;
		@Override
		public void run() {
			while (true) {
				synchronized (ThreadPriorityDemo.class) {
					count++;
					if (count > 10000000) {
						System.out.println("HighPriorityThread is complete." + System.currentTimeMillis());
						break;
					}
				}
			}
		}
	}
	public static class LowPriorityThread extends Thread {
		static int count = 0;
		@Override
		public void run() {
			while (true) {
				synchronized (ThreadPriorityDemo.class) {
					count++;
					if (count > 10000000) {
						System.out.println("LowPriorityThread is complete." + System.currentTimeMillis());
						break;
					}
				}
			}
		}
	}
	public static void main(String[] args) {
		Thread high = new HighPriorityThread();
		Thread low = new LowPriorityThread();
		high.setPriority(Thread.MAX_PRIORITY);
		low.setPriority(Thread.MIN_PRIORITY);
		System.out.println("start:" + System.currentTimeMillis());
		high.start();
		low.start();
	}
}

console

start:1549722133524
LowPriorityThread is complete.1549722134435
HighPriorityThread is complete.1549722134440

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值