在操作系统中,线程可以划分优先级,优先级较高的线程得到的CPU资源较多,也就是说CPU优先执行优先级较高的线程对象的任务
设置线程优先级有助于帮助“线程规划器”确定在下一次选择哪一个线程来优先执行。我们可以使用方法setPriority()方法来设定线程的优先级。
在Java中,线程的优先级分为1~10这10个登记,如果小于1或者大于10,程序都会抛出IllegalArgumentException()。
在JDK中常常使用以下3个常量表示的优先级:
MIN_PRIORITY 1
NORM_PRIORITY 5
MAX_PRIORITY 10
1.线程的优先级具有继承性
所谓的继承性,即线程A启动的线程B会具有和A相同的优先性:
public class ThreadTest {
public static class MyThread extends Thread{
@Override
public void run(){
System.out.println(this.getName() + " : " + this.getPriority());
if(this.getName().equals("A")) {
MyThread t = new MyThread();
t.setName("B");
t.start();
}
}
}
public static void main(String[] args){
MyThread t = new MyThread();
t.setName("A");
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
publicclassThreadTest{
publicstaticclassMyThreadextendsThread{
@Override
publicvoidrun(){
System.out.println(this.getName()+" : "+this.getPriority());
if(this.getName().equals("A")){
MyThreadt=newMyThread();
t.setName("B");
t.start();
}
}
}
publicstaticvoidmain(String[]args){
MyThreadt=newMyThread();
t.setName("A");
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
}
优先级的继承性
2.线程的优先级具有规则性
所谓的规则性,就是高优先级的线程总是比低优先级的线程具有更多被执行的机会,这和线程调用顺序是无关的:
public class ThreadTest {
public static class MyThread extends Thread{
@Override
public void run(){
int result=0 ;
for(int i=0;i<500000;i++){
result ++;
}
System.out.println("线程已经完成了任务,该线程的优先级是" + " : " + this.getPriority());
}
}
public static void main(String[] args){
for(int i=0;i<5;i++){
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
publicclassThreadTest{
publicstaticclassMyThreadextendsThread{
@Override
publicvoidrun(){
intresult=0;
for(inti=0;i<500000;i++){
result++;
}
System.out.println("线程已经完成了任务,该线程的优先级是"+" : "+this.getPriority());
}
}
publicstaticvoidmain(String[]args){
for(inti=0;i<5;i++){
MyThreadt1=newMyThread();
MyThreadt2=newMyThread();
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
}
优先级的规则性体现
3.线程的优先级具有随机性
虽然CPU会尽量将执行资源让给优先级较高的线程,但是因为线程的优先级还具有一定的随机性,不能保证优先级较高的线程每一次都先执行完成。不要把线程的优先级和运行结果的顺序作为衡量的标准,也就是说线程优先级和线程的执行完成顺序无关,他们的关系具有不确定性和随机性。