java之线程优先级

java之线程优先级

  • 优先级:抢cpu的频率,频率高,cpu执行他的次数多。

  • 关键词:setPriority(PRIORITY);

  • 示例代码

    public class myRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i <5 ; i++) {
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName()+"::"+i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    
    public class ThreadTest {
        public static void main(String[] args) {
    
            Thread t1 = new Thread(new myRunnable(),"0");
            Thread t2 = new Thread(new myRunnable(),"1");
            Thread t3= new Thread(new myRunnable(),"2");
            t1.setPriority(Thread.MAX_PRIORITY);
            t2.setPriority(Thread.MIN_PRIORITY);
            t3.setPriority(Thread.NORM_PRIORITY);
            t1.start();
            t2.start();
            t3.start();
    
        }
    }
    
  • 运行结果

    0::0
    2::0
    1::0
    0::1
    2::1
    1::1
    1::2
    2::2
    0::2
    1::3
    0::3
    2::3
    0::4
    1::4
    2::4
    
  • 分析

    • 一般优先级高的会首先执行,一次类推,但是具有偶然性,不一定会按照优先级高低来执行
    • 有不一定会抢到cpu资源,具有可能性;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值