在 Java 中,线程优先级(Thread Priority)用来“建议”操作系统调度线程的先后顺序,但不保证绝对执行顺序(不同 OS 实现不同)。
setPriority(int priority)Thread t = new Thread(() -> {
System.out.println("线程执行");
});
t.setPriority(Thread.MAX_PRIORITY); // 最高优先级
t.start();
Runnable 中设置(推荐)Thread t = new Thread(() -> {
// 任务逻辑
});
t.setPriority(8);
t.start();
Java 定义了 3 个常量:
| 常量 | 值 | 说明 |
|---|---|---|
Thread.MIN_PRIORITY |
1 | 最低优先级 |
Thread.NORM_PRIORITY |
5 | 默认优先级 |
Thread.MAX_PRIORITY |
10 | 最高优先级 |
✅ 合法范围:1 ~ 10
❌ 超出会抛 IllegalArgumentException
t.setPriority(11); // 错误
int p = t.getPriority();
System.out.println(p);
Thread main = Thread.currentThread();
System.out.println(main.getPriority()); // 通常是 5
Runnable r = () -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName());
}
};
Thread t1 = new Thread(r, "低优先级");
Thread t2 = new Thread(r, "高优先级");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
⚠️ 结果不一定“高优先级先跑完”
如果你需要控制执行顺序或并发行为,应使用:
ExecutorServicevolatilesynchronizedLockConditionCountDownLatch / SemaphoreJava 线程优先级可设(1~10),但只是调度建议,不能保证执行顺序。
如果你愿意,我可以帮你写一个线程池 + 优先级队列的实战示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。