Reputation: 857
I set my thread to a higher priority then my other thread, yet it seems as if the CPU time is random? Here is my program below.
public class Main {
public static void main(String[] args){
Priority high=new Priority("High Priority");
Priority low=new Priority("Low Priority");
//set the priorities
high.thread.setPriority(Thread.NORM_PRIORITY + 2);
low.thread.setPriority(Thread.NORM_PRIORITY - 2);
//start the threads
high.thread.start();
low.thread.start();
try {
high.thread.join();
low.thread.join();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("\nHigh Priority thread counted to"+high.count);
System.out.println("\nLow Priority thread counted to"+low.count);
}
}
MyThread Class
public class Priority implements Runnable {
int count;
Thread thread;
static boolean stop = false;
static String currentName;
public Priority(String name){
thread = new Thread(this,name);
count = 0;
//Only one version of currentName as it is static
currentName = name;
}
//Begin the execution of the thread
@Override
public void run() {
System.out.println(thread.getName() + " Starting");
do {
//enter the thread increment the counter
count++;
if (currentName.compareTo(thread.getName()) != 0) {
currentName=thread.getName();
System.out.println("In " + currentName);
}
} while(stop == false && count < 10000000);
stop=true;
System.out.println("\n" + thread.getName() + " terminating.");
}
}
Output to the program varies Sometimes I will get
High Priority thread counted to10000000
Low Priority thread counted to6266009
and other times I will get
High Priority thread counted to4859068
Low Priority thread counted to10000000
Upvotes: 2
Views: 81
Reputation: 27125
There's only two runnable threads during most of the lifetime of your program. If you're running on a computer that has two or more CPUs, then the priorities of those two threads aren't going to make any difference. Priorities only matter when there are more threads that want to run than there are CPUs available for them to run on.
Upvotes: 3