Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting priority to Java's threads

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?

like image 431
Guy Avatar asked Oct 24 '09 13:10

Guy


People also ask

How do I set priority to threads?

It can be changed using the method setPriority() of class Thread. There are three static variables for thread priority in Java i.e. MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY. The values of these variables are 1, 10 and 5 respectively.

Can we change priority of running thread in Java?

The thread priority determines when the processor is provided to the thread as well as other resources. It can be changed using the method setPriority() of class Thread.

What are the priorities given for multithreading?

MAX_PRIORITY − The maximum priority that a thread has, whose default value is 10. NORM_PRIORITY − The default priority that a thread has, whose default value is 5. MIN_PRIORITY − The minimum priority that a thread has, whose default value is 1.


1 Answers

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. } 
like image 79
Macarse Avatar answered Sep 30 '22 21:09

Macarse