一 点睛
每个线程在执行时都具有一定的优先级,优先级高的线程获得较多的执行机会,而优先级低的线程则获得较少的执行机会。
每个线程默认的优先级都与创建它的父线程的优先级相同,在默认情况下,main线程具有普通优先级,由main线程创建的子线程也具有普通优先级。
二 代码
public class PriorityTest extends Thread { // 定义一个有参数的构造器,用于创建线程时指定name public PriorityTest(String name) { super(name); } public void run() { for (int i = 0 ; i < 50 ; i++ ) { System.out.println(getName() + ",其优先级是:" + getPriority() + ",循环变量的值为:" + i); } } public static void main(String[] args) { // 改变主线程的优先级 Thread.currentThread().setPriority(6); for (int i = 0 ; i < 30 ; i++ ) { if (i == 10) { PriorityTest low = new PriorityTest("低级"); low.start(); System.out.println("创建之初的优先级:" + low.getPriority()); // 设置该线程为最低优先级 low.setPriority(Thread.MIN_PRIORITY); } if (i == 20) { PriorityTest high = new PriorityTest("高级"); high.start(); System.out.println("创建之初的优先级:" + high.getPriority()); // 设置该线程为最高优先级 high.setPriority(Thread.MAX_PRIORITY); } } } }三 运行
创建之初的优先级:6 低级,其优先级是:1,循环变量的值为:0 创建之初的优先级:6 低级,其优先级是:1,循环变量的值为:1 高级,其优先级是:6,循环变量的值为:0 高级,其优先级是:10,循环变量的值为:1 ...... 高级,其优先级是:10,循环变量的值为:47 高级,其优先级是:10,循环变量的值为:48 高级,其优先级是:10,循环变量的值为:49 低级,其优先级是:1,循环变量的值为:2 低级,其优先级是:1,循环变量的值为:3 低级,其优先级是:1,循环变量的值为:4 低级,其优先级是:1,循环变量的值为:5 ...... 低级,其优先级是:1,循环变量的值为:45 低级,其优先级是:1,循环变量的值为:46 低级,其优先级是:1,循环变量的值为:47 低级,其优先级是:1,循环变量的值为:48 低级,其优先级是:1,循环变量的值为:49四 说明
从运行效果来看,优先级高的线程获得更多的执行机会。