📅  最后修改于: 2023-12-03 14:51:41.100000             🧑  作者: Mango
在Java多线程中,线程的优先级是一个重要的概念。线程的优先级决定了一个线程在何时得到CPU资源,并且在同等条件下具有更高优先级的线程会比具有较低优先级的线程更容易获得CPU资源。
Java线程的优先级有10个级别,从1到10,其中1是最低优先级,10是最高优先级。
Java提供了三个方法设置线程的优先级。这三个方法分别是:
示例代码:
public class ThreadPriorityDemo {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running");
}
}, "Thread-1");
Thread t2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running");
}
}, "Thread-2");
t1.setPriority(Thread.MIN_PRIORITY); // 设置t1线程的优先级为最低
t2.setPriority(Thread.MAX_PRIORITY); // 设置t2线程的优先级为最高
t1.start();
t2.start();
t1.join();
t2.join();
}
}
上述代码定义了两个线程t1和t2,分别执行了5次输出语句。t1的优先级是最低的,t2的优先级是最高的。运行结果如下:
Thread-2 is running
Thread-2 is running
Thread-1 is running
Thread-2 is running
Thread-1 is running
Thread-2 is running
Thread-1 is running
Thread-2 is running
Thread-1 is running
Thread-2 is running
Java线程优先级是多线程编程中一个非常重要的概念。通过设置线程的优先级可以改变线程获得CPU资源的几率,但是并不能保证一定能够优先执行。因此,在编写多线程程序时,需要注意线程优先级的设置和使用。