目前,我設計一個股票市場的應用程序有以下要求Interrrupt-能夠ScheduledExecutorService的Android中
- 1)掃描股價反覆,有一個固定的睡眠時間。 2)能隨時中斷睡眠。這是因爲當用戶添加新的股票時,我們需要從睡眠中醒來並立即掃描。
此前,我使用裸骨Thread
,以充分滿足上述2個要求。
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
。線程將被喚醒,並立即執行任務。
不過,我覺得很難維護這樣的裸骨代碼,並且容易出錯。我想要使用ScheduledExecutorService
。但是,我沒有能力將Thread從睡眠狀態中喚醒,並立即執行任務。
我想知道,Android中是否有任何類,它使我能夠執行定期任務,如ScheduledExecutorService
?但有能力喚醒線程從睡眠狀態,並立即執行工作。