线程的优先级

63 篇文章 0 订阅

线程的优先级

线程优先级一共有10个等级1-10,1最低,10最高。优先级高的不一定会先执行,只会提高线程执行的权重。可以通过setPriority()和getPriority()去设置获取线程的优先级。主线程的优先级为5。

public class TestPriority {
    public static void main(String[] args) {
        //打印主线程的优先级
        System.out.println(Thread.currentThread().getName() + "->" + Thread.currentThread().getPriority());
        //创建一个线程
        MyPriority myPriority = new MyPriority();
        //创建线程代理对象
        Thread thread1 = new Thread(myPriority);
        Thread thread2 = new Thread(myPriority);
        Thread thread3 = new Thread(myPriority);
        //设置线程优先级并执行
        thread1.setPriority(1);
        thread1.start();

        thread2.setPriority(5);
        thread2.start();

        thread3.setPriority(10);
        thread3.start();

    }

}

class MyPriority implements Runnable {
    @Override
    public void run() {
        //获取并打印线程的优先级
        System.out.println(Thread.currentThread().getName() + "->" + Thread.currentThread().getPriority());
    }
}

通过运行发现,优先级高的线程thread3不一定会先执行。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值