java并发之线程优先级

java中的线程有自己的优先级,优先级高的线程在竞争资源时会更有优势,当然这是一个概率性问题,如果运气不好,高优先级的线程可能也会抢占失败;

java中从1-10表示线程的优先级

    /**
     * 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;

数字越大,优先级越高,下面代码展示了优先级的作用;

package com.example.demo;

import org.junit.Test;

import com.example.demo.PriorityDemo.HightPriority;
import com.example.demo.PriorityDemo.LowPriority;

public class PriorityDemo {

	public static class HightPriority extends Thread {
		static int count = 0;
		public void run(){
			while (true) {
				synchronized (PriorityDemo.class) {
					count++;
					if (count > 10000000) {
						System.out.println("HightPriority is complete");
						break;
					}
				}
			}
		}
	}
	
	public static class LowPriority extends Thread {
		static int count = 0;
		public void run() {
			while(true) {
				synchronized (PriorityDemo.class) {
					count++;
					if (count > 10000000) {
						System.out.println("LowPriority is complete");
						break;
					}
				}
			}
		}
	}
	
	@Test
	public void testPriority() {
		HightPriority hightPriority = new HightPriority();
		LowPriority lowPriority = new LowPriority();
		hightPriority.setPriority(Thread.MAX_PRIORITY);
		lowPriority.setPriority(Thread.MIN_PRIORITY);
		lowPriority.start();
		hightPriority.start();
	}
}

打印结果

HightPriority is complete
LowPriority is complete

上述代码中HightPriority 设置优先级比较高,
大多数情况下会先打印出这段话

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值