每个线程都有一个优先级。
默认情况下,一个线程继承父线程的优先级。
setPriority方法提高或降低任何一个线程的优先级,将线程优先级设置在MIN_PRIORITY(1)与MAX_PRIORITY(10)之间的任何值。NORM_PRIORITY是5。
每当线程调度器有机会选择新线程时,它首先选择较高优先级的线程。但是线程的优先级高度依赖于系统。当虚拟机依赖于宿主平台的线程实现机制时,Java线程的优先级被映射到宿主机平台的优先级上,优先级个数也许更多,又也许会更少。
(例如:Windows有7个优先级,Java有10个优先级,这样就不会一一对应,但是会有Java会有两个优先级与其他优先级共同对应到windows的两个优先级)
不要将程序构建为功能的正确性依赖于优先级。
注意:如果有几个高优先级的线程没有进入非活动状态,低优先级的线程可能永远也不能执行。每当调度器决定运行一个新线程时,首先会在具有高优先级的线程中进行选择,这样会使低优先级的线程完全饿死。
void setPriority(int newPriority)
设置线程的优先级,必须在Thread.MIN_PRIORITY与Thread.MAX_PRIORITY之间,一般使用Thread.NORM_PRIORITY优先级。
static int MIN_PRIORITY
线程最小的优先级,值为1。
static int NORM_PRIORITY
线程默认的优先级,值为5。
static int MAX_PRIORITY
线程最大的优先级,值为10。
static void yield()
导致当前执行线程处于让步状态。如果有其他可运行线程 具有至少与此线程同样高的优先级,那么这些线程接下来会被调度。
代码样例
public class PriorityThread extends Thread {
public PriorityThread(String name){
super(name);
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
Thread currentThread = Thread.currentThread();
System.out.println(currentThread.getName()+"("+currentThread.getPriority()+"),loop "+i);
}
}
}
单元测试
public class PriorityThreadTest {
@Test
public void testPriorityThread(){
Thread currentThread = Thread.currentThread();
System.out.println(currentThread.getName()+"("+currentThread.getPriority()+")");
Thread t1=new PriorityThread("T-1"); // 新建T-1
Thread t2=new PriorityThread("T-2"); // 新建T-2
t1.setPriority(1); // 设置T-1的优先级为1
t2.setPriority(10); // 设置T-2的优先级为10
t1.start(); // 启动T-1
t2.start(); // 启动T-2
}
}
打印结果
通过打印结果可以得知,单元测试这个主线程,优先级别为5。其次先执行了高优先级的T-2,T-2执行完毕后,T-1才开始执行。
印证了:线程默认优先级为5,同一个父线程内,先执行高优先级线程,再执行低优先级线程。