在线程里面有个概念,叫做优先级priority
可以给线程设置优先级,1-10;数字越大,优先级越高
但是:你以为优先级高的一定会优先执行吗?
NONONO
设置优先级按优先级执行,只是给CPU提建议,CPU听不听,看他心情
看代码:
package com.bes.mybatis_plus.Test1.TestPriority;
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);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
//先设置优先级,再启动
t1.start();
t2.setPriority(Thread.MIN_PRIORITY);
t2.start();
t3.setPriority(3);
t3.start();
t4.setPriority(5);
t4.start();
t5.setPriority(7);
t5.start();
t6.setPriority(Thread.MAX_PRIORITY);
t6.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
执行结果,箭头后的数字是优先级,上下顺序表示执行顺序:
main-->5
Thread-0-->5
Thread-5-->10
Thread-4-->7
Thread-2-->3
Thread-3-->4
Thread-1-->1
main-->5
Thread-0-->5
Thread-3-->5
Thread-4-->7
Thread-5-->10
Thread-2-->3
Thread-1-->1
main-->5
Thread-2-->3
Thread-5-->10
Thread-3-->5
Thread-4-->7
Thread-0-->5
Thread-1-->1
从结果可以看出:
并不严格按照优先级执行线程,但是隐约也有趋势,优先级高的先执行