线程的优先级
来源:互联网 发布:经传软件指标全集 编辑:程序博客网 时间: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资源较多,所以他等待的时间较短。
阅读全文
0 0
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 一个线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程的优先级
- 线程函数的优先级
- 线程的优先级
- Java-数据库
- 从 13 年开发史中,谷歌无人车之父预见自动驾驶的未来
- 冒泡排序的改进
- GMIS 2017大会杨洋演讲:认知分析-透过机器重新审视商业本质
- GMIS 2017 大会杨琼演讲:人工智能+医疗——噱头,还是未来?
- 线程的优先级
- 【NOI2015 Day2】荷马史诗 huffman tree结构运用
- GMIS 2017大会俞凯演讲:迈向智能认知型对话交互
- GMIS 2017大会圆桌论坛:探索人工智能的应用场景及商业化
- 10/21.22 练习题
- 1024!程序员节快乐!
- Ubuntu下apt-get安装及卸载jdk
- GMIS 2017大会圆桌论坛:机器智能时代的全球化进程
- [BZOJ1050][HAOI2006]旅行comf(图论)