【发布时间】:2012-03-06 07:20:13
【问题描述】:
public final void sendAdvertisement(final Advertisement advertisment, int delay, final int repetitions){
final ScheduledFuture exec = executor.scheduleAtFixedRate( //<< initialized on this line
new Runnable(){
int totalSends = 0;
public void run(){
//do stuff here
if(++totalSends >= repetitions) exec.cancel(true); //<< here is says exec might not be initialized
}
},
0, delay, TimeUnit.MILLISECONDS);
}
如果无法做到这一点,您能否提出一个更好的方法来做到这一点?我在 ScheduledThreadPoolExecutor 中找不到它的方法。基本上我想要做的是让这段代码运行 3 次然后取消“计时器”。我可能会使用 Swing Timer,但我不想因为它用于其他东西。
它在 cmets 中说,但这是错误:
%PATH%Discovery.java:148: variable exec might not have been initialized
if(++totalSends >= repetitions) exec.cancel(true);
【问题讨论】:
-
最终 ScheduledFeature exec = null; exec = executor.sche... 等等。然后在你的 if(++totalSends) 语句中,添加一个辅助语句 if(exec != null){exec.cancel(true);} ???
-
这不可能,你不能在初始化后改变一个最终变量,即使是空值对吗?
-
哎呀,你是对的。让它不是最终的。
-
没关系,我删除了我的答案,我错了。如果将其设为非最终版本,则无法在可运行文件中访问它。我的错。
-
它必须是有趣的,否则我将无法在匿名内部类中使用它
标签: java multithreading timer threadpool