第十二章 并发

Java编程思想》知识点:

21.2.6 优先级

线程的优先级将该线程的重要性传递给调度器。尽管CPU处理现有线程集的顺序是不确定的,但是调度器将倾向于让优先权最高的线程限制性。但是,优先级较低的线程仅仅是执行的频率较低,不意味优先权较低的线程得不到执行。

在绝大多数时间里,所有线程都应该以默认的优先级运行。试图操作线程优先级通常是一种错误。

复制代码
 1 import java.util.concurrent.*;
 2 public class SimplePriorities implements Runnable {
 3     private int countDown = 5;
 4     private volatile double d;
 5     private int priority;
 6     public SimplePriorities(int priority) {
 7         this.priority = priority;
 8     }
 9     public String toString() {
10         return Thread.currentThread() + ":" + countDown;
11     }
12     public void run() {
13         Thread.currentThread().setPriority(priority);
14         while (true) {
15             for (int i = 0; i < 100000; i++) {
16                 d += (Math.PI + Math.E) / (double) 100000;
17                 if (i % 1000 == 0) {
18                     Thread.yield();
19                 }
20             }
21             System.out.println(this);
22             if (--countDown == 0) {
23                 return;
24             }
25         }
26     }
27     public static void main(String[] args) {
28         ExecutorService exec = Executors.newCachedThreadPool();
29         for (int i = 0; i < 5; i++) {
30             exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
31         }
32         exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
33         exec.shutdown();
34     }
35 }
复制代码
复制代码
运行结果如下:
Thread[pool-1-thread-6,10,main]:5 Thread[pool-1-thread-6,10,main]:4 Thread[pool-1-thread-6,10,main]:3 Thread[pool-1-thread-6,10,main]:2 Thread[pool-1-thread-6,10,main]:1 Thread[pool-1-thread-1,1,main]:5 Thread[pool-1-thread-3,1,main]:5 Thread[pool-1-thread-2,1,main]:5 Thread[pool-1-thread-4,1,main]:5 Thread[pool-1-thread-5,1,main]:5 Thread[pool-1-thread-3,1,main]:4 ...
复制代码

注意:线程优先级是在run()方法的开头部分设定的。

为了保证在多系统下的可移植性:在调整优先级的时候,只使用MAX_PRIORITY、NORM_PRIORITY、MIN_PRIORITY三种级别,即10、5、1。

posted @   淡忘的江南  阅读(120)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示