In the code below, I am trying to get the higher priority thread to run by yielding the lower priority thread. But it doesn’t seem to work, the higher priority thread seems to run after lower priority thread finishes. Can anyone explain what I am doing wrong?
import java.util.ArrayList;
import java.util.List;
public class TestThreadPriority extends Thread {
static List<String> messages = new ArrayList<String>();
public void run() {
Thread t = Thread.currentThread();
int priority = t.getPriority();
String name = t.getName();
messages.add(name + ":" + priority);
Thread.yield();
messages.add(name + ":" + priority);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = Thread.currentThread();
t.setPriority(MIN_PRIORITY);
int priority = t.getPriority();
String name = t.getName();
messages.add(name + ":" + priority);
Thread tp1 = new TestThreadPriority();
tp1.setPriority(MIN_PRIORITY);
Thread tp2 = new TestThreadPriority();
tp2.setPriority(MAX_PRIORITY);
tp1.start();
tp2.start();
Thread.yield();
messages.add(name + ":" + priority);
for(int i = 0; i < messages.size(); i++) {
System.out.println((i+1) + ". " + messages.get(i));
}
}
}
Output is:
- main:1
- Thread-0:1
- Thread-0:1
- main:1
- Thread-1:10
- Thread-1:10
Any help is greatly appreciated.
Thanks,
Quadir
I’d guess that your first thread has finished executing even before the second thread has started. Perhaps if your threads did some real work (or even just slept a bit) you’d see overlapping messages from the two threads.
Another problem with your code is that you are accessing
messagesfrom multiple threads without synchronizing.You also should join with the two threads you’ve started before trying to print the contents of
messages, to ensure that the threads you started have already logged their messages and that they don’t try to modify the list while you’re iterating over it to print it.Once you’ve fixed all this, one final point is that both your threads are yielding, not just the lower priority thread. When the higher priority thread yields, it’s perfectly reasonable that the lower priority thread gets some running time. Having a higher priority doesn’t give you a monopoly. In your simplified code example the priority probably won’t make much difference to what happens – it will be mostly down to chance as to which thread hits the yield statement first.