线程优先级(线程优先级)

来源:互联网 发布:八皇后问题递归c语言 编辑:程序博客网 时间:2024/05/21 19:28
每个线程都有优先级。优先级由1到10之间的数字表示。在大多数情况下,线程根据其优先级(称为抢占式调度)调度线程。但是它不能保证,因为它依赖于JVM规范,它选择哪个调度。

3个常量在Thread类中defiend:

  1. public static int MIN_PRIORITY
  2. public static int NORM_PRIORITY
  3. public static int MAX_PRIORITY
线程的默认优先级为5(NORM_PRIORITY)。MIN_PRIORITY的值为1,MAX_PRIORITY的值为10。

线程优先级示例:

  1. class TestMultiPriority1 extends Thread{
  2.  public void  run(){   
  3.    System.out.println(“运行时线程的名称:” + Thread.currentThread()。getName());  
  4.    System.out.println(“运行时线程的优先级:” + Thread.currentThread().getPriority());  
  5.   
  6.   }  
  7.  public static void  main(String args []){    
  8.   TestMultiPriority1 m1 = new  TestMultiPriority1();  
  9.   TestMultiPriority1 m2 = new  TestMultiPriority1();  
  10.   m1.setPriority(Thread.MIN_PRIORITY);  
  11.   m2.setPriority(Thread.MAX_PRIORITY);  
  12.   m1.start();  
  13.   m2.start();  
  14.    
  15.  }  
  16. }     
现在测试
输出: 运行线程名称为:Thread-0       运行线程的优先级是:10       运行的线程名称是:Thread-1       运行线程的优先级是:1        
原创粉丝点击