线程的优先级
线程优先级一共有10个等级1-10,1最低,10最高。优先级高的不一定会先执行,只会提高线程执行的权重。可以通过setPriority()和getPriority()去设置获取线程的优先级。主线程的优先级为5。
public class TestPriority {
public static void main(String[] args) {
//打印主线程的优先级
System.out.println(Thread.currentThread().getName() + "->" + Thread.currentThread().getPriority());
//创建一个线程
MyPriority myPriority = new MyPriority();
//创建线程代理对象
Thread thread1 = new Thread(myPriority);
Thread thread2 = new Thread(myPriority);
Thread thread3 = new Thread(myPriority);
//设置线程优先级并执行
thread1.setPriority(1);
thread1.start();
thread2.setPriority(5);
thread2.start();
thread3.setPriority(10);
thread3.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
//获取并打印线程的优先级
System.out.println(Thread.currentThread().getName() + "->" + Thread.currentThread().getPriority());
}
}
通过运行发现,优先级高的线程thread3不一定会先执行。