随着代码吼叫我的吐司定期出现(我认为这里找到类似的代码)。当w == 0时,我希望我的吐司每x秒出现一次,否则取消它。问题是,当w时我无法取消祝酒!我用于定期祝酒的代码是:
final Timer timer = new Timer();
final Handler handler = new Handler();
if (w == 0.0) {
final Runnable runnable = new Runnable() {
@Override
public void run() {
t.show();
}
};
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
handler.postDelayed(runnable, 500);
}
}, 500, 1000);
else {
// ?????
在else语句中,我尝试了timer.cancel,removeCallBacks,甚至removeCallBacksAndMessages,但没有任何效果。有什么想法吗?
答案 0 :(得分:0)
使用ScheduledExecutorService代替以下内容:
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Runnable runnable = new Runnable() {
@Override
public void run() {
t.show();
}
};
if (w == 0.0){
final ScheduledFuture<?> future =
scheduler.scheduleAtFixedRate(runnable, 500, 1000, TimeUnit.MILLISECONDS);
}else{
scheduler.shutdownNow();
}
修改强> 我试图复制你想做的事情,这应该有效。我们将期货放在一个清单中,当达到正确的条件时,我们取消一切。
public class Main {
static int MAX_COUNT = 6;
static volatile int counter = 0;
public static void main(String[] args) {
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ArrayList<ScheduledFuture<?>> futures = new ArrayList<>();
final Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Runnuble: "+counter++);
}
};
while(true){
//This avoid counter (and CPU) to go too fast
try {
Thread.sleep(1200);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (counter > MAX_COUNT - 1){
// we cancel everything
for(ScheduledFuture<?> future : futures)
if(!future.isCancelled())
future.cancel(true);
scheduler.shutdown();
break;
}else{
//we put the future in a list
futures.add(scheduler.scheduleAtFixedRate(runnable, 500, 1000, TimeUnit.MILLISECONDS));
}
}
}
}
答案 1 :(得分:0)
您可以使用final List<Float> wList = new ArrayList();
代替foat w
,在这种情况下,它也可以在内部函数中使用。因此,您可以wList.add(newW);
进行修改,并按wList.get(wList.size() - 1)
但这是某种黑客攻击,所以请先看看FMiscia的答案:)