0

I have a thread:

class SomeRunnable implements Runnable {
    @Override
    public void run() {
        while (true) {
            //some code...
            try {
                Thread.sleep(33);
            } catch (InterruptedException e) {
                return;
            }
        }
    }
}

which I start using:

someThread = new Thread(new SomeRunnable());
someThread.setName("SomeThread");
someThread.start();

If I want to stop the thread I simply interrupt it:

someThreat.interrupt();

How can I later resume the thread?

Thank you!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Guy Sharon
  • 47
  • 7

1 Answers1

0

You can use wait() and notify() method.

wait()

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

notify()

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50
  • Thank you, I get the error: "object not locked by thread before wait()" – Guy Sharon Sep 16 '18 at 17:30
  • You have to lock the object before calling notify – Abu Yousuf Sep 16 '18 at 17:35
  • Check this https://stackoverflow.com/questions/26590542/java-lang-illegalmonitorstateexception-object-not-locked-by-thread-before-wait thread – Abu Yousuf Sep 16 '18 at 17:36
  • Thank you! I'll look it up. Other than the fact that I can't resume an interrupted thread, is there any difference between wait() and interrupt()? Also, is there any CPU usage difference between a "waited" thread and an interrupted one? – Guy Sharon Sep 16 '18 at 17:41
  • interrupts are used to stop thread and wait is used to wait a thead until another thread calls notify . You can't use a thread after it goes to stop state. – Abu Yousuf Sep 17 '18 at 04:36