设置 Java 线程的优先级
我有一个在几个线程中运行的程序。主线程与其他线程共享一个对象,并且在主线程中我有一个调用:
synchronized(obj){
do stuff
}
我怀疑主线程饥饿并且无法访问 obj 。如何提高主线程的优先级或者默认情况下它已经高于其他线程?
I have a program that runs in a few threads. The main thread shares an object with the other threads and in the main I have a call to:
synchronized(obj){
do stuff
}
I have a suspicion that the main thread is starved and isn't getting access to obj
. How do I raise the priority of the main thread or is it already higher than the other threads by default?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Thread 类中有一个 setPriority() 方法。
检查此 javadoc。
将线程优先级设置为最大:
You have a setPriority() method in the Thread class.
Check this javadoc.
Setting thread priority to maximum:
此处的系列文章指出了各种平台上线程优先级管理的一些复杂性。
我想知道您的根本问题是否只是您的工作线程非常占用 CPU 资源,因此很少达到它们自然“释放”处理器的程度(例如通过执行一些 IO 或休眠)。如果是这种情况,那么您可能会在这些工作线程中包含对yield()的一些调用,从而给其他线程更多的机会。
The series of articles here indicate some complexities in the management of thread priorities on various platforms.
I wonder if your fundamental problem is simply that your worker threads are very CPU intensive and hence rarely reach a point where they would naturally "let go" of the processor (for example by doing some IO or sleeping.) If such is the case then you might include some calls to yield() in those workers, hence giving other Threads more of a chance.
您可以使用 setPriority() 方法。例如:
这为 bar 提供了新的优先级,它将快速接管 Foo
编辑:
要回答您的评论,您可以使用以下命令设置最大优先级:
you can use the setPriority() method. For example:
This gives bar the new priority which should quickly take over Foo
Edit:
To answer your comment, you can set the max priortiy using:
增加主线程的优先级的方式
Macarse说可能会起作用。但是,您依赖平台的抢占式线程调度程序才能正常工作。当工作线程完成正在运行的任何重要代码部分时,您应该在工作线程中调用 Thread.yield() 静态方法。即使您使用不同级别的线程优先级,这也是一个值得养成的好习惯。
Increasing the main thread's priority the way
Macarse says will probably work. However, you are relying on the platform's preemptive thread scheduler to work properly. You should instead call the
Thread.yield()
static method in your worker threads when they are done with whatever important sections of code they are running. This is a good habit to get into even when you are using different levels of thread priority.正如其他人已经回答的那样,您确实可以按如下方式设置线程的优先级:
但请注意,在您的示例中,线程优先级与线程访问同步对象的顺序无关。
Java 使用其他标准来授予访问权限。
例如,请参阅此。
As others already answered, you can indeed set a priority to a thread as follows:
But please be aware, in your example, that thread priority has nothing to do in which order threads get access to a synchronized object.
Java uses other criteria to give access.
See for example this.