Java 线程优先级
2018-02-28 15:23 更新
Java线程教程 - Java线程优先级
所有线程都有优先级。
优先级由1到10之间的整数表示。
优先级为1的线程优先级最低。优先级为10的线程具有最高优先级。
在Thread类中定义了三个常量来表示下表中列出的三个不同的线程优先级。
| 线程优先级常量 | 整数值 |
|---|---|
| MIN_PRIORITY | 1 |
| NORM_PRIORITY | 5 |
| MAX_PRIORITY | 10 |
具有较高优先级的线程应该有更多的CPU时间。
线程的优先级只是调度器的一个提示。
Thread类的setPriority()方法为线程设置了新的优先级。
getPriority()方法返回线程的当前优先级。
创建线程时,其优先级设置为创建线程的优先级。
例子
以下代码演示如何设置和获取线程的优先级。
public class Main {
public static void main(String[] args) {
Thread t = Thread.currentThread();
System.out.println("main Thread Priority:" + t.getPriority());
Thread t1 = new Thread();
System.out.println("Thread(t1) Priority:" + t1.getPriority());
t.setPriority(Thread.MAX_PRIORITY);
System.out.println("main Thread Priority:" + t.getPriority());
Thread t2 = new Thread();
System.out.println("Thread(t2) Priority:" + t2.getPriority());
// Change thread t2 priority to minimum
t2.setPriority(Thread.MIN_PRIORITY);
System.out.println("Thread(t2) Priority:" + t2.getPriority());
}
}
上面的代码生成以下结果。

以上内容是否对您有帮助:

免费 AI IDE


更多建议: