多线程中的Java线程优先级
在多线程的情况下,线程调度程序会根据线程的优先级将线程分配给特定的进程。Java线程具有预先分配的优先级。除此之外,java虚拟机还可以为线程分配优先级,或者由程序员明确指定优先级。线程优先级的值范围在1到10(含10)之间。与优先级相关的三个静态变量是-
MAX_PRIORITY-线程具有的最大优先级,其默认值为10。
NORM_PRIORITY-线程具有的默认优先级,默认值为5。
MIN_PRIORITY-线程具有的最低优先级,其默认值为1。
Java中的“getPriority()”方法有助于返回绑定的线程的优先级作为其值。
“setPriority()”方法更改给定线程的优先级值。当线程优先级小于1或大于10时,它将引发IllegalArgumentException。
示例
import java.lang.*; public class Demo extends Thread{ public void run(){ System.out.println("Now, inside the run method"); } public static void main(String[]args){ Demo my_thr_1 = new Demo(); Demo my_thr_2 = new Demo(); System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority()); System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority()); my_thr_1.setPriority(5); my_thr_2.setPriority(3); System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority()); System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority()); System.out.print(Thread.currentThread().getName()); System.out.println("The thread priority of main thread is : " + Thread.currentThread().getPriority()); Thread.currentThread().setPriority(10); System.out.println("The thread priority of main thread is : " + Thread.currentThread().getPriority()); } }
输出结果
The thread priority of first thread is : 5 The thread priority of first thread is : 5 The thread priority of first thread is : 5 The thread priority of first thread is : 3 The thread priority of main thread is : 5 The thread priority of main thread is : 10
名为Demo的类从基类Thread继承。定义了功能“运行”并定义了相关消息。在主函数中,创建了Demo类的两个实例,并通过调用函数“getPriority”找到了它们的优先级。
它们被打印在控制台上。接下来,使用“setPriority”功能为Demo实例分配优先级。输出显示在控制台上。线程的名称借助“getName”功能显示在屏幕上。