I have the following code:
public class ThreadTest implements Runnable {
public int ThrCount = 0;
public void ThrCountIncr() {
while (true) {
ThrCount++;
System.out.println(ThrCount);
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void run() {
while (true) {
if (ThrCount > 10) {
System.out.println(ThrCount + "\n Thread finished");
System.exit(1);
}
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
But when I remove this line from run, it stops working:
Thread.currentThread().sleep(100);
First, I start the thread, then I use ThrCountIncr.
ThreadTest Thrtest = new ThreadTest();
Thread thr = new Thread(Thrtest);
thr.start();
Thrtest.ThrCountIncr();
The thread checks the ThrCount variable value, and if it is greater than 10, it stops the program. Without sleep(100), the thread doesn’t stop the program, and I think it doesn’t check the variable value. Why does the call to sleep make this code work?
Even with the
Thread.sleep()it might not work. This is because you don’t properly synchronize accesses to the sharedThrCountvariable.If you make that variable
volatile, you should not see any issues any longer. However it might not loop exactly 10 times as the++operation is not atomic.Ideally, you should use an AtomicInteger and use its
incrementAndGet()method.Also note:
thrCount,thrCountIncr()sleepis a static method so you can simply callThread.sleep(...);and it will sleep in the current thread.