上QQ阅读APP看书,第一时间看更新
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所示。
图1-62 优先级被继承
图1-63 优先级被更改再继续继承