getPriority()和setPriority(int newPriority) 是实例方法
这两个方法用于获取和设置线程的优先级,优先级高的CPU得到的CPU资源比较多,设置优先级有助于帮"线程规划器"确定下一次选择哪一个线程优先执行。换句话说,两个在等待CPU的线程,优先级高的线程越容易被CU选择执行。下面来看一下例子,并得出几个结论:
1.线程的继承性
public class MyThread09_0 extends Thread { public void run() { System.out.println("MyThread9_0 run priority = " + this.getPriority()); } }
public class MyThread09_1 extends Thread { public void run() { System.out.println("MyThread9_1 run priority = " + this.getPriority()); MyThread09_0 thread = new MyThread09_0(); thread.start(); } }
public static void main(String[] args) { System.out.println("main thread begin, priority = " + Thread.currentThread().getPriority()); System.out.println("main thread end, priority = " + Thread.currentThread().getPriority()); MyThread09_1 thread = new MyThread09_1(); thread.start(); }
看一下运行结果:
main thread begin, priority = 5 main thread end, priority = 5 MyThread9_1 run priority = 5 MyThread9_0 run priority = 5
从这个例子我们得出结论:线程默认优先级为5,如果不手动指定,那么线程优先级具有继承性,比如线程A启动线程B,那么线程B的优先级和线程A的优先级相同。
如果A设置了线程优先级为6 , 在A中启动B ,则B的优先级也是一样的
2.线程的规则性
下面的例子演示了设置线程优先级带来的效果:
public class MyThread10_0 extends Thread { public void run() { long beginTime = System.currentTimeMillis(); for (int j = 0; j < 100000; j++){} long endTime = System.currentTimeMillis(); System.out.println("◆◆◆◆◆ thread0 use time = " + (endTime - beginTime)); } }
public class MyThread10_1 extends Thread { public void run() { long beginTime = System.currentTimeMillis(); for (int j = 0; j < 100000; j++){} long endTime = System.currentTimeMillis(); System.out.println("◇◇◇◇◇ thread1 use time = " + (endTime - beginTime)); } }
public static void main(String[] args) { for (int i = 0; i < 5; i++) { MyThread10_0 mt0 = new MyThread10_0(); mt0.setPriority(5); mt0.start(); MyThread10_1 mt1 = new MyThread10_1(); mt1.setPriority(4); mt1.start(); } }
看下运行结果:
◆◆◆◆◆ thread0 use time = 0 ◆◆◆◆◆ thread0 use time = 0 ◆◆◆◆◆ thread0 use time = 1 ◆◆◆◆◆ thread0 use time = 2 ◆◆◆◆◆ thread0 use time = 2 ◇◇◇◇◇ thread1 use time = 0 ◇◇◇◇◇ thread1 use time = 1 ◇◇◇◇◇ thread1 use time = 5 ◇◇◇◇◇ thread1 use time = 2 ◇◇◇◇◇ thread1 use time = 0
看到黑色菱形(线程优先级高的)先打印完,再多试几次也是一样的。为了产生一个对比效果,把yMyThread10_0的优先级设置为4,看下运行结果:
◆◆◆◆◆ thread0 use time = 0 ◇◇◇◇◇ thread1 use time = 1 ◇◇◇◇◇ thread1 use time = 1 ◆◆◆◆◆ thread0 use time = 0 ◇◇◇◇◇ thread1 use time = 0 ◆◆◆◆◆ thread0 use time = 1 ◆◆◆◆◆ thread0 use time = 1 ◇◇◇◇◇ thread1 use time = 2 ◇◇◇◇◇ thread1 use time = 1 ◆◆◆◆◆ thread0 use time = 0
看到,马上差别就出来了。从这个例子我们得出结论:线程的优先级是有一定的规则性的,CPU会尽量将执行资源让给优先级比较高的线程。
3.线程的随机性
上面说到的第二点就是验证线程的规则性,在优先级越相近的情况,线程执行的顺序是随机的,CPU会尽量将执行资源让给优先级比较高的线程这一说法是对的,但是实际运行的情况是多种多样的,所以线程充满了随机性