线程优先级

现代操作系统基本采用时分的形式调度运行的线程,线程分配得到的时间片的多少决定了线程使用处理器资源的多少,也对应了线程优先级这个概念。在JAVA线程中,通过一个int priority来控制优先级,范围为1-10,其中10最高,默认值为5。下面是源码(基于1.8)中关于priority的一些量和方法。

package com.toov5.thread;

class Priority implements Runnable {

      @Override
    public void run() {
        for(int i=0; i<100; i++){
            System.out.println(Thread.currentThread().toString()+"---i"+i);
        }
        
    }

}
public class PriorityThreadTest{
    
    public static void main(String[] args) { 
         Priority priority =  new Priority();
         Thread t1 = new Thread(priority);
         Thread t2 = new Thread(priority);
         //注意设置了优先级,不代表每次都一定会被执行,只是cpu调度会优先分配
         t1.setPriority(10);
         t1.start();
         t2.start();
    }
    
    
}

 

 

 

 

posted @ 2018-10-21 20:51  toov5  阅读(295)  评论(0编辑  收藏  举报