每个线程都有一个优先级。优先级是由1
到10
之间的数字表示。在大多数情况下,线程调度程序根据线程的优先级(称为抢占式调度)来调度线程。 但它不能保证,因为它依赖于JVM规范,它选择哪种调度。
Thread
类中定义的3
个常量:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
线程的默认优先级为5
(NORM_PRIORITY)。 MIN_PRIORITY
的值为1
,MAX_PRIORITY
的值为10
。
线程优先级示例:
package com.zaixian;
class TestMultiPriority1 extends Thread {
public void run() {
System.out.println("running thread name is:" + Thread.currentThread().getName());
System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
}
public static void main(String args[]) {
TestMultiPriority1 m1 = new TestMultiPriority1();
TestMultiPriority1 m2 = new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
执行上面示例代码,得到以下结果:
running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:1
running thread priority is:10