Java线程的优先级学习(1)

文章参考《Java多线程编程核心》

概述:系统中的线程可以划分优先级,优先级越高获取cpu资源多,cpu优先执行。

Java中设置优先级使用方法 Thread 中的 setPriority()方法,设置线程优先级就是告诉线程规划器先拿哪一个线程优先执行

让我们看看setPriority方法的源码:

//Java中 Thread的 setPriority的源码
  public final void setPriority(int newPriority) {
        ThreadGroup g;
        checkAccess();
        if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
            throw new IllegalArgumentException();
        }
        if((g = getThreadGroup()) != null) {
            if (newPriority > g.getMaxPriority()) {
                newPriority = g.getMaxPriority();
            }
            setPriority0(priority = newPriority);
        }
    }

优先级的常量定义:

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

结论: 从这里我们能看到如果线程的优先级如果大于最大线程优先级(MAX_PRIORITY =10),或小于最小优先级(MIN_PRIORITY=1)则会抛出异常IllegalArgumentException;

让我们实验一下:

创建一个 MyThread2.java,把他的优先级设置为-1

public class MyThread2 extends Thread {

    @Override
    public void run() {
        System.out.println("MyThread2 run priority" + this.getPriority());
    }

    public static void main(String[] args) {


        MyThread2 thread2 = new MyThread2();
        thread2.setPriority(-1);
        thread2.start();
    }
}

结果如下:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值