《Java多线程编程核心技术(第2版)》 —1.14 线程的优先级
【摘要】 本节书摘来自华章计算机《Java多线程编程核心技术(第2版)》 一书中第1章,第1.14.1节,作者是高洪岩。
1.14 线程的优先级
在操作系统中,线程可以划分优先级,优先级较高的线程得到CPU资源较多,也就是CPU优先执行优先级较高的线程对象中的任务,其实就是让高优先级的线程获得更多的CPU时间片。
设置线程优先级有助于“线程规划器”确定在下一次选择哪一个线程来优先执行。
设置线程的优先级使用setPriority()方法,此方法在JDK中的源代码如下:
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if ((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
在Java中,线程的优先级分为1~10共10个等级,如果优先级小于1或大于10,则JDK抛出异常throw new IllegalArgumentException()。
JDK使用3个常量来预置定义优先级的值,代码如下:
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
1.14.1 线程优先级的继承特性
在Java中,线程的优先级具有继承性,例如,A线程启动B线程,则B线程的优先级与A线程是一样的。
创建t18项目,创建MyThread1.java文件,代码如下:
package extthread;
public class MyThread1 extends Thread {
@Override
public void run() {
System.out.println("MyThread1 run priority=" + this.getPriority());
MyThread2 thread2 = new MyThread2();
thread2.start();
}
}
创建MyThread2.java文件,代码如下:
package extthread;
public class MyThread2 extends Thread {
@Override
public void run() {
System.out.println("MyThread2 run priority=" + this.getPriority());
}
}
文件Run.java的代码如下:
package test;
import extthread.MyThread1;
public class Run {
public static void main(String[] args) {
System.out.println("main thread begin priority="
+ Thread.currentThread().getPriority());
// Thread.currentThread().setPriority(6);
System.out.println("main thread end priority="
+ Thread.currentThread().getPriority());
MyThread1 thread1 = new MyThread1();
thread1.start();
}
}
程序运行结果如图1-62所示。
将以下注释去掉:
// Thread.currentThread().setPriority(6);
再次运行Run.java文件,程序运行结果如图1-63所示。
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)