天天看點

多線程——優先級 Priority程式

多線程——優先級 Priority程式

程式

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.com/video/BV1V4411p7EF?p=16