gpt4 book ai didi

Java多线程-线程优先级

转载 作者:行者123 更新时间:2023-12-03 02:37:59 26 4
gpt4 key购买 nike

谁能解释一下java中线程优先级是如何工作的。这里的困惑是,如果 java 不能根据线程的优先级保证线程的实现,那么为什么要使用这个 setpriority() 函数。

我的代码如下:

public class ThreadSynchronization implements Runnable{

public synchronized void run() {
System.out.println("Starting Implementation of Thread "+Thread.currentThread().getName());
for(int i=0;i<10;i++)
{
System.out.println("Thread "+Thread.currentThread().getName()+" value : "+i);
}
System.out.println("Ending Implementation of Thread "+Thread.currentThread().getName());
}

public static void main(String[] args) {
System.out.println("Program starts...");
ThreadSynchronization th1 = new ThreadSynchronization();
Thread t1 = new Thread(th1);
t1.setPriority(1);
synchronized(t1)
{
t1.start();
}

ThreadSynchronization th2 = new ThreadSynchronization();
Thread t2 = new Thread(th2);
t2.setPriority(9);
synchronized (t2) {
t2.start();
}

System.out.println("Program ends...");
}
}

在上面的程序中,即使我更改了优先级,我也发现输出没有任何差异。此外,实时应用如何使用线程优先级也会有很大帮助。谢谢。

最佳答案

线程优先级只是操作系统任务调度程序的一个提示,取决于底层操作系统。操作系统会尝试为高优先级线程分配更多资源,但它不保证这一点。因此,如果您的程序依赖于线程优先级,那么您反过来将程序绑定(bind)到底层操作系统,这是不好的。

来自Java Concurrency in Practice :

Avoid the temptation to use thread priorities, since they increase platform dependence and can cause liveness problems. Most concurrent applications can use the default priority for all threads.

关于Java多线程-线程优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com