📜  Java多线程-线程优先级:

📅  最后修改于: 2020-09-27 01:17:43             🧑  作者: Mango

线程优先级(Thread Priority):

每个线程都有一个优先级。优先级由1到10之间的数字表示。在大多数情况下,线程计划会根据线程的优先级来调度线程(称为抢先式调度)。但是不能保证,因为它取决于JVM规范来选择哪种调度。

Thread类中定义了3个常量:

公共静态int MIN_PRIORITY公共静态int NORM_PRIORITY公共静态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