priority
- Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程。线程调度器 按照线程的优先级决定应调度哪个线程来执行。
- 线程的优先级用数字表示,范围从1到10。例如:Thread.MIN_PRIORITY = 1 、 Thread.MAX_PRIORITY = 10 、 Thread.NORM_PRIORITY = 5 。
- 使用下述方法获得或设置线程对象的优先级:int getPriority(); void setPriority(int newPriority);
- 优先级低只是意味着获得调度的概率低。并不是绝对先调用优先级高后调用优先级低的线程。
- 优先级的设定最好在start()前。
测试代码
public class PriorityTest {
public static void main(String[] args){
System.out.println("main线程的优先级" + Thread.currentThread().getPriority());
MyPriority mp = new MyPriority();
Thread t = new Thread(mp);
t.start();
System.out.println(t.getPriority());
Thread t1 = new Thread(mp);
Thread t2 = new Thread(mp);
Thread t3 = new Thread(mp);
Thread t4 = new Thread(mp);
Thread t5 = new Thread(mp);
t1.setPriority(10);
t2.setPriority(8);
t3.setPriority(Thread.MIN_PRIORITY);
t4.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class MyPriority implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName()+"自定义类线程优先级:" + Thread.currentThread().getPriority());
}
}