线程的优先级(线程优先级)
每个线程都有一个优先级。优先级由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。
线程优先级示例:
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();
}
}
Output:running thread name is:Thread-0 running thread priority is:10 running thread name is:Thread-1 running thread priority is:1