admin管理员组

文章数量:1624332

文章目录

    • 优先级Priority
        • 要点:
        • 案例代码:

优先级Priority

要点:

(1)使用getPriority( )和getPriority(int XX)来获取和设置优先级
(2)几个数值
Thread.MIN_PRIORITY = 1
Thread.MAX_PRIORITY = 10
Thread.NORM_PRIORITY = 5
(3)级别越高,不一定就先执行,看cpu,只是级别越高(数值越大)先执行的可能性越大

案例代码:
package com.heima.Multithreading;

public class Priority {
    public static void main(String[] args) {

        //主线程的默认优先级
        System.out.println(Thread.currentThread().getName()+"----->"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();

        Thread t1 = new Thread(myPriority,"t1");
        Thread t2 = new Thread(myPriority,"t2");
        Thread t3 = new Thread(myPriority,"t3");
        Thread t4 = new Thread(myPriority,"t4");
        Thread t5 = new Thread(myPriority,"t5");


        //先设置优先级,再启动
        t1.start();

        t2.setPriority(Thread.MIN_PRIORITY);//MIN_PRIORITY = 1
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(8);
        t4.start();

        t5.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY = 10
        t5.start();

    }
}
class MyPriority implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"----->"+Thread.currentThread().getPriority());
    }
}

本文标签: 优先级Priority