目录
Thread类源码中定义:
最低优先级为1
public final static int MIN_PRIORITY = 1;
一般没有继承,没有显示指定优先级时,默认优先级为5
public final static int NORM_PRIORITY = 5;
最高优先级为10
public final static int MAX_PRIORITY = 10;
1、线程优先级具有继承性
当线程A启动B线程的时候,B线程相当于子线程,A为父线程,那么B线程会继承A的优先级,A优先级=B优先级。如果不想继承优先级,可以设置优先级,setPriority();
class A extends Thread{
@Override
public void run(){
B b = new B(); //创建对象的时候,就已经将b线程的优先级设为A的优先级了。
b.start(); //只是启动而已
}
}
class B extends Thread{ }
2、线程优先级的作用
优先级越高的线程,CPU越是尽量将资源给这个线程,但是并不代表优先级高,就要等着把优先级高的线程执行完了才会去执行优先级低的线程,不是这样的,只是说CPU会尽量执行高优先级线程,低优先级线程也有机会得到执行,只是机会少一些。
假如两个线程,优先级相差越大,这种被执行的差距就越大,优先级相差小的时候,这种被执行的差距就小一些。
举个例子说明:
下面有两个内容一样的线程,只是优先级设置不一样,一个是1,一个是9.
public class LowThread extends Thread {
private int count = 0;
public int getCount(){
return count;
}
@Override
public void run(){
while (true){
count++;
}
}
}
public class HighThread extends Thread {
private int count = 0;
public int getCount(){
return count;
}
@Override
public void run(){
while (true){
count++;
}
}
}
public static void main(String[] args) throws InterruptedException {
LowThread lowThread = new LowThread();
HighThread highThread = new HighThread();
highThread.setPriority(8);
lowThread.setPriority(1);
lowThread.start();
highThread.start();
Thread.sleep(1000);
lowThread.stop();
highThread.stop();
System.out.println("lowThread:"+ lowThread.getCount());
System.out.println("highThread:"+ highThread.getCount());
}
这个线程的运行时在电脑比较闲的情况下测试的,测试了好多次,9级线程的count总是大于1级线程的count。
说明:高优先级线程被运行的时间总是大于低优先级的线程,就是优先级高,被运行的机会大。