我只想创建另一个线程,我需要让它继续做某事,直到单击按钮A,然后单击按钮B时恢复,仅此而已。

Thread t = new Thread(new Runnable(){

@Override

public void run(){

while(bool) { .... }

}});

t.start();


这是我要遵循的格式。我从onCreate开始,但是如何暂停和恢复线程?

最佳答案

使用wait()notifyAll()

示例代码供您了解:

class myRunnable implements somethingRunnable {
    private Object mPauseLock;
    private boolean mPaused;
    private boolean mFinish;

    public myRunnable() {
        mPauseLock = new Object();
        mPaused = false;
        mFinish = false;
    }

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

            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();
        }
    }

}


希望能帮助到你 :)

10-08 06:36