简介
Java提供了一个线程调度器来监控程序启动后进去就绪状态的所有线程。线程调度器通过线程的优先级来决定调度哪些线程执行。一般来说,Java的线程调度器采用时间片轮转算法使多个线程轮转获得CPU的时间片。然而根据实际情况,每个线程的重要程序也不相同,有时候我们想让一些线程优先执行,那么我们可以将他的优先级调高一下,这样它们获得的时间片会多一些。
多个线程处于就绪状态时,若这些线程的优先级相同,则线程调度器会按时间片轮转方式或独占方式来分配线程的执行时间。
优先级级别
java中线程优先级用1~10来表示,分为三个级别:
低优先级:1~4,其中类变量Thread.MIN_PRORITY最低,数值为1;
默认优先级:如果一个线程没有指定优先级,默认优先级为5,由类变量Thread.NORM_PRORITY表示;
高优先级:6~10,类变量Thread.MAX_PRORITY最高,数值为10。
如何使用
Thread t1 = new Thread(() -> {}});
t1.setPriority(Thread.MAX_PRIORITY);
t1.start()
注意
不是高优先级的线程就一定先比低优先级执行完,而是高优先级线程先执行的概率比低优先级的线程高。
案例
public class ThreadSimpleAPI2 {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
Optional.of(Thread.currentThread().getName() + "-Index" + i).ifPresent(System.out::println);
}
});
t1.setPriority(Thread.MAX_PRIORITY);
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
Optional.of(Thread.currentThread().getName() + "-Index" + i).ifPresent(System.out::println);
}
});
t2.setPriority(Thread.NORM_PRIORITY);
Thread t3 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
Optional.of(Thread.currentThread().getName() + "-Index" + i).ifPresent(System.out::println);
}
});
t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
}