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