目前,我正在设计具有以下要求的股票市场应用程序
以前,我使用裸骨
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
。但是,我缺乏将线程从 sleep 状态唤醒并立即执行工作的能力。我想知道,Android中是否有任何类可以像
ScheduledExecutorService
一样定期执行任务?但是具有将线程从 sleep 状态唤醒并立即执行工作的能力。 最佳答案
这是我用ScheduledThreadPoolExecutor
的解决方案。要取消现有任务,请对从future.cancel()
返回的Future对象发出scheduleAtFixedRate()
。然后在scheduleAtFixedRate()
设置为0的情况下再次调用initial delay
。
class HiTask implements Runnable {
@Override
public void run() {
System.out.println("Say Hi!");
}
}
// periodically execute task in every 100 ms, without initial delay time
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
long initialDelay = 0;
long period = 100;
ScheduledFuture<?> future1 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS);
// to trigger task execution immediately
boolean success = future.cancel(true); // mayInterruptIfRunning = true: interrupt thread even task has already started
ScheduledFuture<?> future2 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS);