Java线程优先级

线程的优先级:

1、Max_PRIORITY :10

2、Min_PRIORITY:1

3、NORM_PRIORITY:5(此为默认优先级)

如何获得和设置当前线程的优先级:

getPriority():获得当前线程的优先级;

setPriority():设置当前线程的优先级。

注意:高优先级的线程要抢占低优先级线程的cpu的执行权,但是只是从概率上讲,高优先级的线程高概率情况下被执行,这并不意味着只有当高优先级的线程执行完后低优先级的线程才执行。

//创建一个类实现Runnable接口
class MyPriority implements Runnable{

    //重写run()方法
    @Override
    public void run() {

        System.out.println(Thread.currentThread().getName() + ":重写run()方法");
    }
}

public class ThreadPriority {

    public static void main(String[] args) {
        MyPriority priority = new MyPriority();

        Thread thread = new Thread(priority);
        Thread thread1 = new Thread(priority);
        Thread thread2 = new Thread(priority);

//      输出线程Thread-0的优先级
        System.out.println(thread.getPriority());

//      修改线程Thread-1的优先级为MAX_PRIORITY并输出
        thread1.setPriority(Thread.MAX_PRIORITY);
        System.out.println(thread1.getPriority());

//      修改线程Thread-2的优先级为MIN_PRIORITY并输出
        thread2.setPriority(Thread.MIN_PRIORITY);
        System.out.println(thread2.getPriority());

        thread.start();
        thread1.start();
        thread2.start();
    }

}

输出结果:每次运行结果都不一定相同,且高优先级并不一定先执行,印证了上面的注意事项

5
10
1
Thread-0:重写run()方法
Thread-1:重写run()方法
Thread-2:重写run()方法

Process finished with exit code 0

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值