学习过程观看视频:[狂神说Java]
https://www.bilibili.com/video/BV1V4411p7EF?p=3
欢迎大家支持噢,很良心的老师了!
java代码
package com.zjl;
/**
* Created by zjl
* 2020/11/17
**/
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);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
//先设置优先级,再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY); //MAX_PRIORITY=10
t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
}
}
结果:
说明:
1、并不是优先级越大,一定最先执行。
2、由于不太好模拟线程同时启动,导致线程启动有顺序,CPU执行速度太快,所以导致执行顺序和启动顺序一致。
3、当线程同时执行时,优先级越高,确实先执行的概率越高。