简体   繁体   中英

How to pause and resume a Thread?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM