我想暂停正在通过迭代消息列表在文件中写入消息的线程。当消息列表为空时,我希望线程停止并在列表中有消息时恢复线程。
我知道 stop、suspend ()、resume 方法已被弃用,但如果线程持续在后台运行,它会消耗 cpu。我做了很多谷歌搜索,但找不到正确的答案。请任何人帮助我
这是我的代码:
private Thread mFileWriterThread = new Thread() {
@Override
public synchronized void run() {
while (mIsRunning) {
synchronized (mMessageList) {
Iterator it = mMessageList.iterator();
while ((it.hasNext())) {
String message = (String) it.next();
writeToFile(fileOutputStream, message);
mMessageList.remove(message);
}
}
}
}
};
最佳答案
这就是 BlockingQueue存在于。它有一个 take()强制线程阻塞直到对象可用的方法。您的问题可以通过简单的生产者-消费者设计来解决。
我在此处粘贴了从 Oracle 示例中摘录的一小段代码:
class Producer implements Runnable {
private final BlockingQueue queue;
Producer(BlockingQueue q) { queue = q; }
public void run() {
try {
while (true) { queue.put(produce()); }
} catch (InterruptedException ex) { ... handle ...}
}
Object produce() { ... }
}
class Consumer implements Runnable {
private final BlockingQueue queue;
Consumer(BlockingQueue q) { queue = q; }
public void run() {
try {
while (true) { consume(queue.take()); }
} catch (InterruptedException ex) { ... handle ...}
}
void consume(Object x) { ... }
}
当然,消费者和生产者必须以某种方式共享队列(只需将其传递给构造函数,如示例所示即可正常工作)。
关于java - 如何暂停正在运行的线程并在需要时重新启动同一线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21060758/