I was learning Multithreading in Java and though to measure the relative CPU usage of two threads hi and lo on the below code.
class Clicker implements Runnable{
long click=0;
Thread t;
private volatile boolean running =true;
public Clicker(int p)
{
t=new Thread(this);
t.setPriority(p);
}
public void run(){
while(running){
click++;
}
}
public void stop(){
running =false;
}
public void start(){
t.start();
}
}
public class HiLoPri {
public static void main(String[] args) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Clicker hi = new Clicker(Thread.NORM_PRIORITY +2);
Clicker lo = new Clicker(Thread.NORM_PRIORITY -2);
lo.start();
hi.start();
try{
Thread.sleep(10000);
}catch(InterruptedException e){
System.out.println("Main Thread interrupted. ");
}
lo.stop();
hi.stop();
try{
hi.t.join();
lo.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted Exception Caught");
}
System.out.println("Low priority : " + lo.click);
System.out.println("High priority : " + hi.click);
}
}
Here's are the outputs for various priorities:
- lo = NORM_PRIORITY -2 and hi = NORM_PRIORITY +2 : Low priority : 1725664879, High priority : 1774465713 || High/Low = 1.02827
- lo = NORM_PRIORITY -4 and hi = NORM_PRIORITY +4 : Low priority : 2142378792, High priority : 2180156175 || High/Low = 1.01763
- lo = NORM_PRIORITY and hi = NORM_PRIORITY : Low priority : 2582216343 , High priority : 2581415280 || High/Low = 0.99968
From output 3, I understood in two threads of equal priority, the first one gets slighly more peference.
In the case of output 1 and output 2, see the priority values. When the priority difference became high, counts incresed. But when I set the difference 0 (in output 3), as contrary to the above observation, counts shows an increase instead of descrease.
Can you explain why?
(Specs : Java SE 7, AMD A10 quad core 2.3GHz and Window 8)