admin管理员组

文章数量:1624344

程序

package thread;


/*
线程优先级 PRIORITY ,优先级分 10 个等级,
等级 1 为最低等级 Thread.MIN_PRIORITY (最后跑)
等级 5 为中等等级 Thread.NORM_PRIORITY
等级 10 为最高等级 Thread.MAX_PRIORITY (最先跑)
等级不能小于 1 大于 10 。

注意:优先级低只是意味着获得调度的概率低,并不是优先级低就不会
     提前调用了,这还是要看 CPU 的调度,有可能优先级低的会提
     前调度。该作用是提升先执行的概率,并不是 100%
*/
public class PriorityTest implements Runnable{

    @Override
    public void run() {//重写 run 方法
        System.out.println(Thread.currentThread().getName());//输出当前线程的名字
    }

    public static void main(String[] args) {
        PriorityTest priorityTest = new PriorityTest();// 实例化 PriorityTest 类

        Thread thread1 = new Thread(priorityTest,"线程——>1");//实例化一个线程 thread1 对象为 priorityTest ,名字为 1
        Thread thread2 = new Thread(priorityTest,"线程——>2");
        Thread thread3 = new Thread(priorityTest,"线程——>3");
        Thread thread4 = new Thread(priorityTest,"线程——>4");
        Thread thread5 = new Thread(priorityTest,"线程——>5");
        Thread thread6 = new Thread(priorityTest,"线程——>6");
        Thread thread7 = new Thread(priorityTest,"线程——>7");
        Thread thread8 = new Thread(priorityTest,"线程——>8");
        Thread thread9 = new Thread(priorityTest,"线程——>9");
        Thread thread10 = new Thread(priorityTest,"线程——>10");

        thread1.setPriority(Thread.MIN_PRIORITY);// MIN_PRIORITY = 1 ,填写 1 也可以
        thread1.start();//开始 线程 thread1 

        thread2.setPriority(2);
        thread2.start();

        thread3.setPriority(3);
        thread3.start();

        thread4.setPriority(4);
        thread4.start();

        thread5.setPriority(Thread.NORM_PRIORITY);// NORM_PRIORITY = 5
        thread5.start();

        thread6.setPriority(6);
        thread6.start();

        thread7.setPriority(7);
        thread7.start();

        thread8.setPriority(8);
        thread8.start();

        thread9.setPriority(9);
        thread9.start();

        thread10.setPriority(Thread.MAX_PRIORITY);// Thread.MAX_PRIORITY = 10
        thread10.start();
    }

}

https://www.bilibili/video/BV1V4411p7EF?p=16

本文标签: 优先级多线程Priority