Skip to content

线程的优先级

  • 线程的优先级是一个整数,范围是1~10,1是最低优先级,10是最高优先级。线程的优先级默认是5,可以通过setPriority(int newPriority)方法设置线程的优先级。
  • 线程的优先级不是绝对的,只是一个相对的参考值,具体的调度由操作系统决定。
  • 线程的优先级可以通过getPriority()方法获取。
  • 线程的优先级可以通过Thread.MIN_PRIORITYThread.NORM_PRIORITYThread.MAX_PRIORITY这三个常量来设置。
  • 线程的优先级的使用示例如下:
java
public class PriorityDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("Hello from thread1!");
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("Hello from thread2!");
            }
        });
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread1.start();
        thread2.start();
    }
}