views:

254

answers:

3

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?

thanks

+1  A: 

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.

djna
+1  A: 

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.
}
Macarse
so you're saying - in every thread I create do setPriority(minimum). Is there a way you know of to set the main thread's priority to maximum? and does it make a difference?
Guy
I edited my post with how to set max priority to your main thread.I don't think it will make a difference. I really don't know what you are doing but Java threads shouldn't need you to change priorities to avoid starvation.
Macarse
A: 

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 );
northpole
but you're setting MAX_PRIORITY to the thread and not the main thread.
Guy
just set the thread you want to me min to MIN_PRIORITY etc...
northpole