你能帮忙解决这个问题吗,为什么它不在 运行 线程中求和?

Could u help solve the problem, why is it not summing in run thread?

变量totalTime不变。 我能做什么?

static volatile long totalTime = 0;

private void initTimer() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            totalTime += 1000;
        }
    }, 1000);
}

这段代码重现了我的问题:

public class Main {

    public static volatile long totalTime = 0;

    public static void main(String ... args){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                totalTime +=1000;
            }
        }, 1000);
        for (int i = 0; i<10; i++) {
            System.out.println(totalTime);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.getStackTrace();
            }
        }
    }

}

当前输出:

0
0
1000
1000
1000
1000
1000
1000
1000
1000

我需要得到这个:

0
1000
2000
3000
...

你的根本问题是你调用了错误版本的 schedule

time.schedule(timerTask, delay)

在指定的延迟后执行一次任务
你想要这个版本:

time.schedule(timerTask, delay, period)

在指定的delay后执行任务,重复执行此后每隔period.

的任务

另外,为了得到你想要的输出,你需要确保主线程和定时器线程的唤醒时间不要太接近,所以你应该通过最初休眠一半的时间来抵消它们。

试试这个:

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        totalTime += 1000;
    }
}, 1000, 1000);

try {
    Thread.sleep(500);
} catch (InterruptedException e) {
    e.getStackTrace();
}

for (int i = 0; i < 10; i++) {
    System.out.println(totalTime);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.getStackTrace();
    }
}