java中,线程优先级有1~10,10个级别。设置优先级小于1或大于10,抛出异常IllegalArgumentException()。
setPriority() 设置线程优先级
优先级常量
public final static int MIN_PRIORITY=1;
public final static int NORM_PRIORITY=5;
public final static int MAX_PRIORITY=10;
线程优先级的特点:
1 继承性 :线程t1中启动线程t2,则默认线程t2优先级与t1相同。
2 规则性 :系统资源尽量先分配给优先级高的,优先级高的线程先执行完的可能性大
3 随机性 :优先级的高的不一定先执行完,资源的分配不是严格按照优先级分配的,因此具有随机性。
另外,线程执行速度,与代码的编写顺序无关。不一定先启动的就先执行完。
示例:
package threadTest7;
public class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1 run priority= " + this.getPriority());
MyThread2 thread2= new MyThread2();
thread2.start();
}
}
package threadTest7;
public class MyThread2 extends Thread{
@Override
public void run() {
System.out.println("MyThread2 run priority= " + this.getPriority());
}
}
package threadTest7;
public class Run {
public static void main(String[] args){
System.out.println("main Thread begin priority= " + Thread.currentThread().getPriority());
// Thread.currentThread().setPriority(11);
Thread.currentThread().setPriority(7);
System.out.println("main Thread end priority= " + Thread.currentThread().getPriority());
MyThread1 thread1 = new MyThread1();
thread1.start();
}
}
结果:
main Thread begin priority= 5
main Thread end priority= 7
MyThread1 run priority= 7
MyThread2 run priority= 7
《Java多线程编程核心技术》 高洪岩