线程优先级

什么是线程优先级?

线程的优先级就是告诉程序每个线程的重要程度。如果有大量的线程被堵塞,都在等待运行,程序会尽可能地运行优先级高的那个线程。但是并不代表优先级低的线程不会运行,只是说优先级低的线程被允许执行的概率会比高优先级线程允许执行的概率低。

查看Thread源码可以看到,线程优先级最大是10, 最小是1 ,默认是5,一般情况下推荐使用下面三个常量,不要自行设置数值。

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

 

下面看两个简单的例子

1.未设置优先级是运行两个线程

public class PriorityDemo {

    public static void main(String[] args)  {
        Thread thread1 = new Thread(()->{
            while (true){
                try {
                    Thread.sleep(300l);
                    System.out.println(Thread.currentThread().getName());
                }catch (InterruptedException e){
                    e.printStackTrace();

                }
            }

        },"线程1");


        Thread thread2 = new Thread(()->{
            while (true) {
                try {
                    Thread.sleep(300l);
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程2");


        thread1.start();
        thread2.start();

    }
}

运行结果:

线程2
线程1
线程2
线程1
线程2
线程1
线程2
线程1

2.设置最大最小等级的两个线程

public class PriorityDemo {

    public static void main(String[] args)  {
        Thread thread1 = new Thread(()->{
            while (true){
                try {
                    Thread.sleep(300l);
                    System.out.println(Thread.currentThread().getName());
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }

        },"线程1");


        Thread thread2 = new Thread(()->{
            while (true) {
                try {
                    Thread.sleep(300l);
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程2");

        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        thread2.start();

    }
}

运行结果:

线程2
线程2
线程1
线程2
线程1

  通过查看上面两个简单的例子,发现基本符合上面的理论说明。

  不同的平台,对线程优先级的支持不同。编程的时候,不要过度的依赖线程的优先级。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值