Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread code not work properly without Thread.sleep(...) call

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?

like image 458
kden Avatar asked Jan 30 '26 08:01

kden


2 Answers

Even with the Thread.sleep() it might not work. This is because you don't properly synchronize accesses to the shared ThrCount variable.

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:

  • Java naming conventions: variables and method names should start in lower case (thrCount, thrCountIncr()
  • sleep is a static method so you can simply call Thread.sleep(...); and it will sleep in the current thread.
like image 131
assylias Avatar answered Feb 01 '26 23:02

assylias


If your thread doesn't sleep, other threads may not be able to work, so the the loop inside ThrCountIncr may get stuck at any time (probably at its first sleep or at the println).

Never have a thread looping without any kind of sleep or wait.

Note also that ThrCount++; may fail if you don't protect it using a synchronization, as it's not an atomic operation.

like image 29
Denys Séguret Avatar answered Feb 01 '26 23:02

Denys Séguret