线程的优先级

来源:互联网 发布:经传软件指标全集 编辑:程序博客网 时间:2024/04/30 11:38

在操作系统中,线程可以划分多个优先级,优先级较高的线程可以得到更多的cpu资源。在java语言中设置线程
优先级使用setPriority()方法,该方法的源码如下:

public final void  setPriority(int newPriority){    ThreadGroup g;    checkAccess();    if(newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY){       throw new IllegalArgumentException();    }   if((g =getTheadGroup())) != null){       if(newPriority > g.getMaxPriority()){           newPriority = g.getMaxPriority();        }   }   setPriority0(priority = newPriority)}

另外,获取线程优先级的方法为getPriority()
在java中线程分为(1~10)10个等级,如果设置的值超出这范围,则会抛出异常IllegalArgumentException。
在java中使用3个常量来预置定义优先级的值,如下:
public final static int MIN_PRIORITY =1;
public final static int MAX_PRIORITY =10;
public final static int NORM_PRIORITY = 5;

java中线程优先级具有如下特点:
1.线程优先级具有继承性
如: A线程启动B线程,则B线程的优先级与A是一样的。

class Thread1 extends Thread{    @Override    public void run(){         System.out.println("子线程的优先级为 :" + Thread.currentThread().getPriority());    }}public class Thread_test {    public static void main (String[] args){                Thread.currentThread().setPriority(8);          System.out.println("主线程的优先级为 :" + Thread.currentThread().getPriority());          Thread1 thread = new Thread1();          thread.start();    } }

这里写图片描述
从上面例子可以可看到主子线程的优先级都为8。

2.优先级具有规则性
操作系统会尽量将cpu资源分配给优先级较高的资源,但是也不是一定要让高优先级的线程执行完成后才分配给下一优先级的线程, 他会在一段时间内按照某种规则来分配cup资源,但是肯定的是优先级高的获得cpu资源的是时间越多。

class Thread1 extends Thread{    @Override    public void run(){        try{            for(int i = 0 ;i < 5; i++) {                System.out.println("线程1的优先级为 :" + Thread.currentThread().getPriority() +                            " i = " + i);                this.sleep(100);            }        }catch(InterruptedException e){        }    }}class Thread2 extends Thread{        @Override        public void run(){            try{                for(int i = 0 ;i < 5; i++) {                    System.out.println("线程2的优先级为 :" + Thread.currentThread().getPriority() +                                " i = " + i);                    this.sleep(100);                }            }catch(InterruptedException e){            }        }}public class Thread_test {    public static void main (String[] args){        Thread1 thread1 = new Thread1();        thread1.setPriority(9);        thread1.start();        Thread2 thread2 = new Thread2();        thread2.setPriority(5);        thread2.start();   }}

这里写图片描述

从上面例子可以可看到线程1的优先级比线程2高,但是线程1在执行的过程中线程2也在执行。如果我们将线程1,2 中的循环次数变大,比如 i=50000,再统计下线程1,2各自的运行时间,可以看出线程1运行时间比线程2短,因为线程1的优先级高,系统分给他的CPU资源较多,所以他等待的时间较短。

原创粉丝点击