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