Thread Running negative number of time.

Hi All,

I wrote a program to check the effects of Thread priority, however to my surprise the output is weired the higher priority thread shows that it run negative number of time, below is the code.

package javaProg.completeReferance;

class Clickerimplements Runnable

{

Thread t;

int click;

volatileboolean running =true;

public Clicker(int pro)

{

t=new Thread(this);

click = 0;

t.setPriority(pro);

}

publicvoid run()

{

while (running)

{

click++;

}

}

publicvoid start()

{

t.start();

}

publicvoid stop()

{

running=false;

}

}

publicclass TestClicker

{

publicstaticvoid main(String [] args)

{

Clicker thread1 =new Clicker(Thread.NORM_PRIORITY+2);

Clicker thread2=new Clicker(Thread.NORM_PRIORITY-2);

thread1.start();

thread2.start();

System.out.println("Processing");

try

{

Thread.sleep(10000);

}

catch (InterruptedException i)

{

System.out.println(i);

}

thread1.stop();

thread2.stop();

try

{

thread1.t.join();

thread2.t.join();

}

catch (InterruptedException i)

{

System.out.println(i);

}

System.out.println("The number of Time Thread1 executed is "+thread1.click);

System.out.println("The number of time Thread2 executed is "+thread2.click);

}

}

Here is the Output..

C:\Users\pravin>java javaProg.completeReferance.TestClicker

Processing

The number of Time Thread1 executed is -386946835

The number of time Thread2 executed is 837375311

Thanks!!

[3461 byte] By [confused_in_javaa] at [2007-11-27 11:37:50]
# 1

No. That's called overflow.

cotton.ma at 2007-7-29 17:16:44 > top of Java-index,Java Essentials,New To Java...
# 2

Thanks a lot , I changed int click to long and its working fine.I am wondering why the Java Platform didnt throw an error or exception for overflow.

confused_in_javaa at 2007-7-29 17:16:44 > top of Java-index,Java Essentials,New To Java...
# 3

> Thanks a lot , I changed int click to long and its

> working fine.I am wondering why the Java Platform

> didnt throw an error or exception for overflow.

Because the Java specification calls for it not to do that but instead to do what you saw and rollover.

cotton.ma at 2007-7-29 17:16:44 > top of Java-index,Java Essentials,New To Java...