線程優(yōu)先級分為10個等級,主線程優(yōu)先級不變,優(yōu)先級越高代表執(zhí)行的順序越靠前,但不排除出現(xiàn)優(yōu)先級低的線程先運行。
線程若想設置優(yōu)先級,必須先設置再啟動?。?!
package com.example.demo.thread;
/**
* @projectName: demo
* @package: com.example.demo.thread
* @className: TestPriority
* @author:
* @description: 測試線程的優(yōu)先級
* @date: 2021/12/7 22:06
*/
public class TestPriority {
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.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.NORM_PRIORITY);
t4.setPriority(7);
t5.setPriority(3);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":------------------>"+Thread.currentThread().getPriority());
}
}

第一次執(zhí)行

第二次執(zhí)行

第N次執(zhí)行