Best Method to pause a Thread?

I have a Runnable class which performs an operation continuously in its run method using an infinite while loop. Sometimes a user might want to pause/resume the operation. What is the best method to pause the Thread. I have two thoughts:

FIRST

class Foo extends Runnable {
    @Override
    public void run() {
    while(true) {
        if(pauseFlag)
           try{
              Thread.sleep();
           } catch(InterrruptedException ie) {//...}
    }
}

SECOND

class Foo extends Runnable {
    @Override
    public void run() {
        while(true) {
            //pause if user wants to pause
            while(pauseFlag);
        }
    }
}
  • In the FIRST case, when i use Thread.sleep inside loop the Netbeans IDE issues warning not to use Thread.sleep inside loop. Why is that?
  • In the SECOND case, when i use infinite empty while loop, is that a performance overhead?
  • Which method(mentioned above or otherwise) should i prefer to pause the action being performed by the Thread according to the users choice?

Because it has nothing to do with synchronization, i do not want to use wait/notify.

Jon Skeet
people
quotationmark

Because it has nothing to do with synchronization, i do not want to use wait/notify.

It has everything to do with synchronization. Presumably your user interaction occurs on a different thread - so you're trying to synchronize signals between the two threads.

You shouldn't use Thread.sleep or a tight loop here. Either wait/notify or something similar using a higher-level construct in java.util.concurrent is the right approach here.

Note that without any memory barriers, changes to your pauseFlag from one thread may not be noticed in a different thread, so you'd at least want to make it volatile.

people

See more on this question at Stackoverflow