3

I am calling a thread inside while loop to sleep for 1 sec. While the flag is true, loop will be running (flag is true for infinite time). Inside the loop thread should sleep for 1 second, wakes up and increase the counter, checks the IF condition and on FALSE condition it should sleep again for 1 sec and the process continues 29 times. On the 30th iteration IF condition will be true and the method called inside IF statement will collect and store a data. Finally on the 32nd iteration method called inside second IF statement will send the stored data to the server and sets the count = 0. The problem is, sometimes sleep thread is sleeping for more than 1 min or sleeps for indefinite time period. Find here my enclosed piece of code.

public class NetworkThread implements Runnable {
private boolean flag;

public NetworkThread(boolean bool) {
    flag = bool;
    isrunning();
}

private boolean isrunning() {
    return flag;
}

int counter = 0;

@Override
public void run() {
    sendStartPacket();
    while (flag) {
        try {
            Thread.sleep(1000);
            counter++;
            if (counter % 30 == 0) {
                // TODO Auto-generated method store an information
            }
            if (counter % 32 == 0) {
                // TODO Auto-generated method send the information to server
            }
        } catch (Exception e) {
            e.toString();
        }
    }
}

private void sendStartPacket() {
    // TODO Auto-generated method stub

}
Rudra
  • 383
  • 3
  • 17
  • 1
    There may be an issues with your catch code. Your only doing an e.toString() which doesn't show anything and your exception ends up being ignored. Might want to change that to log the error to console or file. The title of your issue might shed some doubt on the Thread.sleep functionality. Rest assured that Thread.sleep(1000) will only sleep for 1 second no no more. – Mike Murphy Jan 07 '16 at 12:08

3 Answers3

0

Apart from the complexity of your code/implementation, keep in mind that Thread.sleep() will try to sleep at least for x time, so it isn't strange that it's sleeping "more".

You can get more info about the accuracy of Thread.sleep() in this SO question.

This is the explanation for the case when your app seems to sleep more than desired. For indefinite sleep, I'm with Mike Murphy's comment, check your catch blocks

Community
  • 1
  • 1
webo80
  • 3,365
  • 5
  • 35
  • 52
  • Actually it doesn't guarantee that. If the thread is interrupted, it will sleep less than the time wanted. – Kayaman Jan 07 '16 at 12:22
0

Reset your counter! in the missing final clause and rewrite your check if (counter >= 30)

bluevoid
  • 1,274
  • 13
  • 29
0

If your thread is interrupted, the counter is not increased and the thread sleeps for another 1000 ms. Perhaps that is the reason to your problem?

Ridcully
  • 23,362
  • 7
  • 71
  • 86