java基础--java线程的优先级

线程的优先级

  • MAX_PRIORITY:10
  • MIN_PRIORITY: 1
  • NORM_PRIORITY :5 --> 默认优先级

涉及方法

  • getPriority() :获取线程的优先级。
  • setPriority( int new Priority): 设置线程的优先级。
  • 设置优先级要在该线程开始之前设置。

  下面一段代码中利用上述的两个方法进行了设置和获取优先级。其中 “thread” 线程优先级为 10 ,而“主线程” 的优先级为 1 但是在运行结果中,仍然有主线程比thread 先打印输出。所以高优先级只是概率会比低优先级会多一点,并不能说高优先级一定会比低优先级先运行。

package ThreadMethodTest;
class MyThread extends Thread{
    public MyThread(String s) {
        this.setName(s);
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() );
        }
    }
}

public class ThreadTest {
    public static void main(String[] args) {
        MyThread thread = new MyThread("thread");
        thread.setPriority(Thread.MAX_PRIORITY);
        thread.start();

        Thread.currentThread().setName("主线程");
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        for (int i = 0 ;i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() );
        }

    }
}

运行截图
在这里插入图片描述
其他

  • 线程创建时继承父线程的优先级
  • 低优先级只是获得调度的概率低,并非一定低在高优先级线程之后才会被调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值