如何暂停和恢复线程?

How to pause and resume a Thread?

我有一个线程:

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

我开始使用:

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

如果我想停止线程,我只需中断它:

someThreat.interrupt();

我以后如何恢复线程?

谢谢!

您可以使用wait() and notify()方法。

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.