线程的优先级
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
优先级高的线程有更大的概率先执行,但并不保证优先级高的线程一定先执行。
线程的优先级用数字来表示,范围从1~10。默认的优先级为5。
- Thread.MIN_PRIORITY = 1;
- Thread.Max_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
使用以下方式改变或获取优先级:
- getPriority()
- setPriority()
示例:
package com.jiuhong.thread;
public class TestPriority {
public static void main(String[] args) {
MyPriority myPri = new MyPriority();
Thread t1 = new Thread(myPri,"1");
Thread t2 = new Thread(myPri,"2");
Thread t3 = new Thread(myPri,"3");
t1.setPriority(1);
t1.start();
t2.setPriority(10);
t2.start();
t3.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
}
}