(13)21.2.6 优先级

来源:互联网 发布:英雄联盟辅助软件 编辑:程序博客网 时间:2024/05/17 03:42
1. 线程的优先级
       线程的优先级将该线程的重要性传递给调度器。CPU处理现有线程的顺序的顺序是不确定的,但是调度器将倾向于优先权最高的线程先执行。这不意味着优先权较低的线程不执行(也就是说,这不是死锁)。仅仅是优先级较低的线程执行的频率低。
      在大多数情况下线程应该以默认的优先级进行执行,操作线程优先级是一中错误。
package c21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimplePriorities implements Runnable {
       private int countDown = 5;
       private volatile double d;
       private int priority ;
       public SimplePriorities(int priority){
             this.priority = priority;
      }
       public String toString(){
             return Thread.currentThread() + ": " + countDown ; //记录当前线程的名称和当前线程的创建是第几个。
      }
       public void run() {
            Thread. currentThread().setPriority(priority); //设置当前线程的优先级
             while(true ){
                   for(int i = 1; i < 100000; i++){
                         d += (Math. PI + Math.E)/(double)i;
                         if(i%1000 == 0){
                              Thread. yield();
                        }
                  }
                  System. out.println(this);
                   if(--countDown == 0) return;
            }
      }

       public static void main(String[] args) {
            ExecutorService exec = Executors. newCachedThreadPool();
             for(int i = 0; i < 5; i++){
                  exec.execute( new SimplePriorities(Thread.MIN_PRIORITY ));
            }
            exec.execute( new SimplePriorities(Thread.MAX_PRIORITY));
      }

}

/**
 * 输出结果
 * Thread[pool- 1-thread -6,10,main]: 5
Thread[pool-1 -thread- 3,1,main]: 5
Thread[pool-1 -thread- 4,1,main]: 5
Thread[pool-1 -thread- 2,1,main]: 5
Thread[pool-1 -thread- 5,1,main]: 5
Thread[pool-1 -thread- 1,1,main]: 5
Thread[pool-1 -thread- 6,10,main]: 4
Thread[pool-1 -thread- 4,1,main]: 4
Thread[pool-1 -thread- 6,10,main]: 3
Thread[pool-1 -thread- 3,1,main]: 4
Thread[pool-1 -thread- 2,1,main]: 4
Thread[pool-1 -thread- 1,1,main]: 4
Thread[pool-1 -thread- 5,1,main]: 4
Thread[pool-1 -thread- 6,10,main]: 2
Thread[pool-1 -thread- 4,1,main]: 3
Thread[pool-1 -thread- 3,1,main]: 3
Thread[pool-1 -thread- 4,1,main]: 2
Thread[pool-1 -thread- 6,10,main]: 1
Thread[pool-1 -thread- 5,1,main]: 3
Thread[pool-1 -thread- 2,1,main]: 3
Thread[pool-1 -thread- 1,1,main]: 3
Thread[pool-1 -thread- 3,1,main]: 2
Thread[pool-1 -thread- 1,1,main]: 2
Thread[pool-1 -thread- 5,1,main]: 2
Thread[pool-1 -thread- 2,1,main]: 2
Thread[pool-1 -thread- 4,1,main]: 1
Thread[pool-1 -thread- 3,1,main]: 1
Thread[pool-1 -thread- 1,1,main]: 1
Thread[pool-1 -thread- 5,1,main]: 1
Thread[pool-1 -thread- 2,1,main]: 1

 *
 */
   通过调用Thread.currentThread()来获取对去顶该任务的Thread对象的引用。
   可以看到最后一个线程优先级最高,其余线程优先级最低。注意优先级是在run的头部进行设置的。在构造器中进行设置没有任何好处因为Executor在此刻还没有执行任务。
   在例子中加入运算是为了线程有运算的时间去执行别的线程,这样能够看到优先级较高的线程先执行。
   JDK有10个线程优先级,但是它与多数的操作系统都不映射的很好,如windows有7个优先级。所以这种映射关系是不确定的。
   唯一可以移植的方法是当调用优先级的时候只是用:MAX_PRIORITY,MIN_PRIORITY,NORM_PRIORITY。
原创粉丝点击