在多线程应用程序中,每个线程都分配有一个优先级。线程调度程序根据线程的优先级将处理器分配给该线程,即,优先级最高的线程首先分配给处理器,依此类推。值为' 5'的线程的默认优先级。我们可以使用Thread类的getPriority() 方法获得线程的优先级。
Thread类中为线程优先级定义的三个静态值
这是最大线程优先级,值为10。
这是默认的线程优先级,值为5。
这是最小线程优先级,值为1。
public final int getPriority()
public class ThreadPriorityTest extends Thread {
public static void main(String[]args) {
ThreadPriorityTest thread1 = new ThreadPriorityTest();
ThreadPriorityTest thread2 = new ThreadPriorityTest();
ThreadPriorityTest thread3 = new ThreadPriorityTest();
System.out.println("Default thread priority of thread1: " + thread1.getPriority());
System.out.println("Default thread priority of thread2: " + thread2.getPriority());
System.out.println("Default thread priority of thread3: " + thread3.getPriority());
thread1.setPriority(8);
thread2.setPriority(3);
thread3.setPriority(6);
System.out.println("New thread priority of thread1: " + thread1.getPriority());
System.out.println("New thread priority of thread2: " + thread2.getPriority());
System.out.println("New thread priority of thread3: " + thread3.getPriority());
}
}输出结果
Default thread priority of thread1: 5 Default thread priority of thread2: 5 Default thread priority of thread3: 5 New thread priority of thread1: 8 New thread priority of thread2: 3 New thread priority of thread3: 6