线程优先级确定何时将处理器提供给线程以及其他资源。可以使用setPriority()
Thread类的方法进行更改。
Java中有三个用于线程优先级的静态变量,即MIN_PRIORITY,MAX_PRIORITY和NORM_PRIORITY。这些变量的值分别为1、10和5。
演示此过程的程序如下:
public class ThreadDemo extends Thread { public void run() { System.out.println("Running..."); } public static void main(String[] args) { ThreadDemo thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); System.out.println("Default thread priority of Thread 1: " + thread1.getPriority()); System.out.println("Default thread priority of Thread 2: " + thread2.getPriority()); thread1.setPriority(MAX_PRIORITY); thread2.setPriority(MIN_PRIORITY); System.out.println("\nThe maximum thread priority of Thread 1 is: " + thread1.getPriority()); System.out.println("The minimum thread priority of Thread 2 is: " + thread2.getPriority()); System.out.println("\n" + Thread.currentThread().getName()); System.out.println("Default thread priority of Main Thread: " + Thread.currentThread().getPriority()); Thread.currentThread().setPriority(MAX_PRIORITY); System.out.println("The maximum thread priority of Main Thread is: " + Thread.currentThread().getPriority()); } }
输出结果
Default thread priority of Thread 1: 5 Default thread priority of Thread 2: 5 The maximum thread priority of Thread 1 is: 10 The minimum thread priority of Thread 2 is: 1 main Default thread priority of Main Thread: 5 The maximum thread priority of Main Thread is: 10