R
Ravi
Code:
class NewThread implements Runnable {
long counter=0;
Thread t;
private volatile boolean running = true;
NewThread(String threadName, int priority) {
t = new Thread(this,threadName);
t.setPriority(priority);
}
public void run() {
while (running)
counter++;
}
public void stop() {
running = false;
}
}
class PriorityDemo {
public static void main(String args[]) {
NewThread n1 = new
NewThread("n1",Thread.MAX_PRIORITY);
NewThread n2 = new
NewThread("n2",Thread.MIN_PRIORITY);
n1.t.start();
n2.t.start();
try {
Thread.sleep(10000);
} catch(InterruptedException e) {
System.out.println(e);
}
n1.stop();
n2.stop();
try {
n1.t.join();
n2.t.join();
} catch(InterruptedException e) {
System.out.println(e);
}
System.out.println("n1.counter = "+n1.counter);
System.out.println("n2.counter = "+n2.counter);
System.out.println("difference = "+(n1.counter-
n2.counter));
}
}
this code is to demonstrate the use of priority levels in the Java,
by conting how many times the vaiable counter gets incremented in each
loop.
i compiled it with jdk6 and run it under jre6 in Linux 2.6.19 kernel.
but sometimes i get a -ve diffrence. Can sb pls explain how this
happens as i ve used the man and min priority here.