Hello, two Threads one with High priority and other with low priority access same method run to increase the click count, after 10 sec they both display the click count. According to the program the High Priority thread should get maximum CPU access time and should have more click count than low priority thread but the result is opposite most of the time. Threads are handled differently under different OS, I'm on Windows 7, is this the issue? OR am i doing something wrong? Thanks
class clicker extends Thread{
long click=0;
Thread t;
private volatile boolean flag=true;
public clicker(int p) {
t= new Thread(this);
t.setPriority(p);
}
@Override
public void run() {
while(flag){
click++;
}
}
public void fullstop(){ // didn't used stop name as Thread class also has a final stop method so can't override it
flag=false;
}
@Override
public void start(){
t.start();
}
}
public class ThreadPriority {
public static void main(String args[]){
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker c1 = new clicker(Thread.NORM_PRIORITY+2);
clicker c2 = new clicker(Thread.NORM_PRIORITY-4);
c1.start();
c2.start();
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadPriority.class.getName()).log(Level.SEVERE, null, ex);
}
c1.fullstop();
c2.fullstop();
try {
c1.t.join();
c2.t.join();
} catch (InterruptedException ex) {
Logger.getLogger(ThreadPriority.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("High Priority Thread " +c1.click );
System.out.println("Low Priority Thread " +c2.click );
}
}