-1

So what's the best way to pause a thread? So far I have something like this: In main loop of the thread, first line is:

while (paused == true) {
   Thread.sleep(refreshRate);
}

And it works perfercly. I can change paused state pressing P key. But Im looking for better, more professional solution. I know about reentrant locks and conditions. So I could use them on the thread. And then presing P would release singalAll() method. But it would slow my app a lot because of synchronization which I don't really need in this thread. So what is the best, most perform way to solve it? Maybe using synchronization blocks?

synchronized (new Object()) {

}

Then just part of code would be synchronized. Or maybe I should use semaphores?

3 Answers3

1

You should use a wait/notify scheme such as:

  1. Create an atomic boolean flag in the thread to be paused.
  2. When the flag is set the thread should call wait() on a lock object
  3. When you want to unpause the thread reset the flag and call notify() on the lock object
DSJ
  • 106
  • 3
0

Use wait() and notify()

Object waitLock = new Object();

//...


// waiter Thread
synchronized (waitLock) {
   waitLock.wait();
}


// wake up with

waitLock.notify();
BenMorel
  • 34,448
  • 50
  • 182
  • 322
AlexWien
  • 28,470
  • 6
  • 53
  • 83
0

Use a PauseableThread like the one I posted a while ago in answer to a question much like yours.

It uses ReadWriteLocks to implement so you don't have the overhead of synchronization.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213