Setting priority to Java's threads

半腔热情 提交于 2019-11-26 20:46:25
Macarse

You have a setPriority() method in the Thread class.

Check this javadoc.

Setting thread priority to maximum:

public static void main(String args[]) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    // Your main code.
}

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.

you can use the setPriority() method. For example:

new MyThread("Foo").start(); 
Thread bar = new MyThread("Bar"); 
bar.setPriority( Thread.NORM_PRIORITY + 1 ); 
bar.start();

This gives bar the new priority which should quickly take over Foo

Edit:

To answer your comment, you can set the max priortiy using:

bar.setPriority( Thread.MAX_PRIORITY );
Lorek

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.

Sigi

As others already answered, you can indeed set a priority to a thread as follows:

Thread.currentThread().setPriority(priority);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!