首页 > 解决方案 > 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 线程结束。我想要一种方法来访问计数变量或在某个计数值处停止计时器。请帮我。

标签: javatimer

解决方案


一个解决方法,除了使用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);
    }

推荐阅读