Thread线程的优先级

线程的优先级别在Thread的源码里边可以看到,是一个priority属性,通过翻译过来也是优先级的意思,在Thread的源码种可以看到在类里边

最小的是1,最大的是10,默认值是5,可以做个小实验来进行验证一下

public class Demo {

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getPriority());
    }
}

不设置线程优先级别的时候,默认就是5,

需要特别说明一下优先级别高的线程不一定先执行,优先级别高只是说抢到cpu进行执行的可能性大一点

做个小实验

public class PriorityDemo {

    public static void main(String[] args) throws InterruptedException {
        ThreadDemo[] threads = new ThreadDemo[10];
        //创建10个线程,设置优先级别
        for (int i = 0; i < threads.length; i++) {
            ThreadDemo thread = new ThreadDemo("线程"+i);
            thread.setPriority(i+1);
            threads[i] = thread;
        }
        //开启十个线程
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        //main线程停一秒进行,等待线程执行count++
        Thread.sleep(1000);
        //手动停止十个线程,因为是死循环
        for (int i = 0; i < threads.length; i++) {
            threads[i].stop();
            System.out.println("线程名称 "+threads[i].getName()+" 优先级别 "+ threads[i].getPriority()+" count值 "+threads[i].count);
        }
    }

    static class ThreadDemo extends Thread{

        public ThreadDemo(String name){
            super(name);
        }
        public long count = 0;

        @Override
        public void run() {
            while (true){
                count++;
            }
        }
    }
}

结果展示

通过结果展示优先级别的高的线程获得cpu时间片的时间一定越多。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值