我有以下线程代码在睡眠时发送消息。我暂停它有一些麻烦。我怎么能这样做?我看不到id,我不想停止所有线程,只有这个。
new Thread() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
Message m5 = d.obtainMessage();
d.sendMessage(m5);
}
}
}.start();
答案 0 :(得分:0)
只需创建一个类并使用它的方法onPause
和onResume
。
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();
}
}
}
这可以帮助你。
答案 1 :(得分:0)
暂停线程只需从wait()
。{/ p>调用Thread
然后致电notify()
继续。