主要概念:
java 中的每个线程都有一个关联的优先级,该优先级会影响该线程相对于其他正在运行的线程接收的 cpu 时间量。使用 setpriority(int level) 和 getpriority() 方法配置优先级。级别范围从 1 (min_priority) 到 10 (max_priority),默认为 5 (norm_priority)。
虽然优先级会影响调度,但资源锁和操作系统实现等其他因素也会影响执行。
代码解释
以下代码演示了如何配置和观察优先级的影响:
// demonstra as prioridades das threads.
class priority implements runnable {
int count;
thread thrd;
static boolean stop = false;
static string currentname;
// construtor para criar uma nova thread
priority(string name) {
thrd = new thread(this, name);
count = 0;
currentname = name;
}
// define o comportamento da thread
public void run() {
system.out.println(thrd.getname() + " starting.");
do {
count++;
if (!currentname.equals(thrd.getname())) {
currentname = thrd.getname();
system.out.println("in " + currentname);
}
} while (!stop && count < 10000000);
stop = true; // interrompe outras threads ao alcançar 10.000.000
system.out.println("\n" + thrd.getname() + " terminating.");
}
}
class prioritydemo {
public static void main(string args[]) {
// cria duas threads com diferentes prioridades
priority mt1 = new priority("high priority");
priority mt2 = new priority("low priority");
// configura as prioridades
mt1.thrd.setpriority(thread.norm_priority + 2); // alta prioridade
mt2.thrd.setpriority(thread.norm_priority - 2); // baixa prioridade
// inicia as threads
mt1.thrd.start();
mt2.thrd.start();
try {
mt1.thrd.join();
mt2.thrd.join();
} catch (interruptedexception exc) {
system.out.println("main thread interrupted.");
}
// exibe os resultados
system.out.println("\nhigh priority thread counted to " + mt1.count);
system.out.println("low priority thread counted to " + mt2.count);
}
}
程序中发生了什么?
具有不同优先级的线程:
线程 mt1 的优先级高于 mt2。
这意味着mt1有更大的机会访问cpu,但不是绝对保证。
计数循环和线程切换:
每个线程递增一个计数变量,直到达到 10,000,000。
如果一个线程先完成,静态变量 stop 会停止另一个线程。
交替观察:
当执行在线程之间切换时显示线程名称(currentname)。
优先级和结果:
在典型示例中,高优先级线程运行速度更快,达到 10,000,000 的目标,而其他线程则被中断。
示例输出
High Priority starting. In High Priority Low Priority starting. In Low Priority In High Priority High Priority terminating. Low Priority terminating. High priority thread counted to 10000000 Low priority thread counted to 8183
观察点:
本系统经过多次升级改造,系统内核经过多次优化组合,已经具备相对比较方便快捷的个性化定制的特性,用户部署完毕以后,按照自己的运营要求,可实现快速定制会费管理,支持在线缴费和退费功能财富中心,管理会员的诚信度数据单客户多用户登录管理全部信息支持审批和排名不同的会员级别有不同的信息发布权限企业站单独生成,企业自主决定更新企业站信息留言、询价、报价统一管理,分系统查看分类信息参数化管理,支持多样分类信息,
0

以上就是线程优先级的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号