java - Java Timer:在封闭范围内定义的局部变量计数必须是最终的或有效的最终
问题描述
这是我的代码,
public void sendSMS() throws InterruptedException {
int count=0;
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Sending Client SMS At: "+Calendar.getInstance().getTime());
System.out.println("Sending SMS");
count++;
if(count>=4) {
System.out.println("Cancelling timer Thread");
cancel();
}
}
};
Timer timer = new Timer("TimerThread");
timer.schedule(task, 0, 2000l);
}
我想在 count=4 时停止计时器。但是 count 变量在内部类中是不可访问的。根据我的要求,停止 Timer 应该发生在新启动的计时器线程内(在 run 方法内),因为外部线程不能等到 Timer 线程结束。我想要一种方法来访问计数变量或在某个计数值处停止计时器。请帮我。
解决方案
一个解决方法,除了使用AtomicInteger
是使用一个数组
public void sendSMS() throws InterruptedException {
final int[] count = new int[] {0};
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("Sending Client SMS At: " + Calendar.getInstance().getTime());
System.out.println("At Some Conditions Sending SMS and repeat");
if (count[0] >= 4) {
count[0]++;
System.out.println("Cancelling timer Thread");
cancel();
}
}
};
Timer timer = new Timer("TimerThread");
timer.schedule(task, 0, 2000l);
}
推荐阅读
- java - Firebase 自动短信检索在 Firebase 身份验证中不起作用
- python - 特定日期的过滤器组
- reactjs - 反应表未从网络请求加载
- c - 用 typedef 定义结构有什么区别?
- azure - 如何断开 GitHub 与 Azure 数据工厂 V2 的连接以启用“复制数据”功能?
- nlp - 窗口大小如何影响word2vec,我们如何根据不同的任务选择窗口大小?
- rust - 将 Gstreamer Bin 与 Rust 中的 Ghostpads 连接起来
- user-interface - Kv 相关问题 - 如何将 on_press/release 函数绑定到 recycleview 的视图类?
- python - “click”python cli 模块显示错误 main() got an unexpected keyword argument 'get'
- android - 在 Android 应用程序的 Manifest 文件中声明不相关权限的后果是什么?