【发布时间】:2017-02-28 06:24:55
【问题描述】:
目前,我正在设计一个具有以下要求的股票市场应用程序
- 1) 反复扫描股价,固定休眠时间。
- 2) 可以随时中断睡眠。这是因为当用户添加新股票时,我们需要从睡眠中醒来,并立即扫描。
以前,我使用裸骨Thread 来完全满足上述两个要求。
private class StockMonitor extends Thread {
@Override
public void run() {
final Thread thisThread = Thread.currentThread();
while (thisThread == thread) {
// Fetch stock prices...
try {
Thread.sleep(MIN_DELAY);
} catch (java.lang.InterruptedException exp) {
if (false == refreshed()) {
/* Exit the primary fail safe loop. */
thread = null;
break;
}
}
}
}
public synchronized void refresh() {
isRefresh = true;
interrupt();
}
private synchronized boolean refreshed() {
if (isRefresh) {
isRefresh = false;
// Interrupted status of the thread is cleared.
interrupted();
return true;
}
return false;
}
}
当我想执行要求(2)时,我会打电话给refresh。线程将被唤醒,并立即执行作业。
但是,我觉得这种裸露的 Thread 代码很难维护,而且很容易出错。
我更喜欢使用ScheduledExecutorService。但是,我无法将线程从睡眠状态中唤醒并立即执行工作。
我想知道,Android 中是否有任何类可以让我定期执行ScheduledExecutorService 中的任务?却有能力将线程从休眠状态唤醒,并立即执行工作。
【问题讨论】:
标签: java android multithreading