多线程的优先级问题
重点:理解线程优先级的继承性、规则性、随机性
线程的优先级
在操作系统中,线程可以划分优先级,。尽可能多的给优先级高的线程分配更多的CPU资源。
线程的优先级分为1~10,有三个预定义常量:
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;//默认
public final static int MAX_PRIORITY = 10;
优先级继承性
优先级具有继承性(由线程a启动的线程b的优先级与a相同),比较简单,略。
优先级的规则性
这里的规则性,指的是高优先级的线程往往能获得更多的CPU资源,更快的执行完(当然不是必然,“随机性”)
下面测试说明:
先继承Thread创建PriorityThread
package foreverly.cn.chapter1;
import java.util.Random;
public class PriorityThread extends Thread {
private String show;
public PriorityThread(String show) {
super();
this.show = show;
}
@Override
public void run() {
long beginTime = System.currentTimeMillis();
long addResult = 0;
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 50000; i++) {
Random random = new Random();
random.nextInt();
addResult = addResult + i;
}
}
long endtime = System.currentTimeMillis();
System.out.println(show + " " + "时间:" + (endtime - beginTime));
}
}
再创建测试
package foreverly.cn.chapter1;
public class TestPrority {
public static void main(String[] args) {
for (int i = 0; i<5; i++) {
PriorityThread thread1 = new PriorityThread("1 1 1 1 1 1");
PriorityThread thread2 = new PriorityThread("2 2 2 2 2 2 ");
thread1.setPriority(10);
thread2.setPriority(1);
thread1.start();
thread2.start();
}
}
}
多运行几次,运行结果为:
第一次:
1 1 1 1 1 1 时间:1344
1 1 1 1 1 1 时间:1344
1 1 1 1 1 1 时间:1457
1 1 1 1 1 1 时间:1466
1 1 1 1 1 1 时间:1483
2 2 2 2 2 2 时间:1544
2 2 2 2 2 2 时间:1546
2 2 2 2 2 2 时间:1557
2 2 2 2 2 2 时间:1558
2 2 2 2 2 2 时间:1559
线程thread1的优先级高于thread2,优先执行完。
第二次:
1 1 1 1 1 1 时间:1126
1 1 1 1 1 1 时间:1406
2 2 2 2 2 2 时间:1601
1 1 1 1 1 1 时间:1616
2 2 2 2 2 2 时间:1644
2 2 2 2 2 2 时间:1644
1 1 1 1 1 1 时间:1650
1 1 1 1 1 1 时间:1661
2 2 2 2 2 2 时间:1661
2 2 2 2 2 2 时间:1666
但这种优先具有随机性,而非必然优先。从第二次输出结果来看,总体还是thread1运行快,但是也有thread2比thread1运行快的情况。下面介绍线程的随机性。
线程的随机性
优先级具有随机性!是一种“趋势”而非“必然”。
我们可以通过设置优先级的方式,让CPU尽量将执行资源分配给优先级较高的线程,但是这并不意味着优先级高的线程一定先执行完,这是因为线程的优先级还具有“随机性”,也就是说线程优先级较高的线程不一定每次都先执行完(注意:这并不一定是由线程任务量导致的,即使任务量相同的情况下优先级低的线程也有可能先执行完)。
从上面的第二次的输出结果可以看出,所有线程执行的任务量是相同的 ,但还是出现了优先级低的thread2比优先级高的thread1先执行完的情况。
似乎上了贼船,偏偏又心甘情愿。