Java高并发学习(五)

Java高并发学习(5)

先干重要的事:线程优先级

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

在java中使用1到10表示线程的优先级。一般用静态标量表示:

public final static int MIN_PRIORITY = 1;

public final static int MIN_PRIORITY = 1;

数字越大优先级越高,但有限范围在1到10之间。下面代码展示了优先级的作用。高优先级的线程倾向于更快的完成。


public class fist{
    public final static int MIN_PRIORITY = 1;
    public final static int MAX_PRIORITY = 10;
    public static class MyThread_H extends Thread{
        static int count = 0;
        @Override
        public void run(){
            while(true){
                synchronized (this) {
                    count++;
                    if(count>100000){
                        System.out.println("HightPriority is complete");
                        break;
                    }
                }
            }
        }
    }
    public static class MyThread_L extends Thread{
        static int count = 0;
        @Override
        public void run(){
            while(true){
                synchronized (this) {
                    count++;
                    if(count>100000){
                        System.out.println("LowPriority is complete");
                        break;
                    }
                }
            }
        }
    }
    
    public static void main(String args[]) throws InterruptedException {
        MyThread_H h = new MyThread_H();
        MyThread_L l = new MyThread_L();
        h.setPriority(MAX_PRIORITY);
        l.setPriority(MIN_PRIORITY);
        h.start();
        l.start();
    }
}


上述代码的两个线程,分别设置优先级为1和10,然后让他们完成相同的工作,也就是把count从0加到100000,完成后打印一个提示信息,这样就知道谁先完成了工作了。

这里要注意,在对count累加前,我们使用synchronized产生了一次资源竞争。目的是为了使优先级的差异表现的更明显。

大家尝试运行上诉的代码,可以看到,高优先级的线程在大部分情况下,都会首先完成任务,但不能保证所情况下都是这样。
--------------------- 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值