线程优先级
- 线程调度器按照线程
优先级
来决定应调度那个线程来执行 - 优先级的设定建议在
start()
调用前 - 优先级低只是表示获得调度的概率低,并不是绝对先调用优先级高的线程后调用优先级低的
- 优先级不代表绝对的调度先后顺序
- 优先级用数值 1 - 10 来表示
- Thread类提供了三个常量
- NORM_PRIORITY —— 5 默认
- MIN_PRIORITY —— 1
- MAX_PRIORITY —— 10
// 设置线程对象的优先级
Thread t1 = new Thread(线程对象);
t1.setPriority(Thread.MAX_PRIORITY);
// 获取线程对象的优先级
Thread.currentThread().getPriority()
示例:
package com.tsymq.thread.threadmore;
public class ThreadPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "优先级: " + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
ThreadPriority tp = new ThreadPriority();
Thread t1 = new Thread(tp, "a");
Thread t2 = new Thread(tp, "b");
Thread t3 = new Thread(tp, "c");
Thread t4 = new Thread(tp, "d");
Thread t5 = new Thread(tp, "e");
Thread t6 = new Thread(tp, "f");
// 在调用start()之前设置优先级
t1.setPriority(10);
t2.setPriority(10);
t3.setPriority(10);
t4.setPriority(1);
t5.setPriority(1);
t6.setPriority(1);
// 开启线程
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
结果:
c优先级: 10
d优先级: 1
a优先级: 10
b优先级: 10
e优先级: 1
f优先级: 1
其中a、b、c线程的优先级为10,d、e、f的为1,结果d还是在a、b之前获得了调度