如何在Android中暂停/恢复线程?

Mic*_*ele 32 multithreading android

我有一个运行到活动的线程.当用户单击主页按钮或者例如用户接收到呼叫电话时,我不希望线程连续运行.所以我想暂停线程并在用户重新打开应用程序时恢复它.我试过这个:

protected void onPause() {
  synchronized (thread) {
    try {
      thread.wait();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  super.onPause();
}
protected void onResume() {
  thread.notify();
  super.onResume();
}
Run Code Online (Sandbox Code Playgroud)

它停止线程但不恢复它,线程似乎冻结了.

我也试图与过时的方法Thread.suspend()Thread.resume(),但在这种情况下进入Activity.onPause()该线程不会停止.

谁知道解决方案?

Wro*_*lai 63

使用wait()notifyAll()正确使用锁.

示例代码:

class YourRunnable implements Runnable {
    private Object mPauseLock;
    private boolean mPaused;
    private boolean mFinished;

    public YourRunnable() {
        mPauseLock = new Object();
        mPaused = false;
        mFinished = false;
    }

    public void run() {
        while (!mFinished) {
            // Do stuff.

            synchronized (mPauseLock) {
                while (mPaused) {
                    try {
                        mPauseLock.wait();
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }

    /**
     * Call this on pause.
     */
    public void onPause() {
        synchronized (mPauseLock) {
            mPaused = true;
        }
    }

    /**
     * Call this on resume.
     */
    public void onResume() {
        synchronized (mPauseLock) {
            mPaused = false;
            mPauseLock.notifyAll();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)