java之线程优先级

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29726359/article/details/87560685

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资源,具有可能性;

猜你喜欢

转载自blog.csdn.net/qq_29726359/article/details/87560685