我有以下代码。我在ScheduledExecuterService方法中使用scheduleNumbers()来显示一系列随机数,持续指定的毫秒数。但是,我似乎无法更新在curNumber lambda中显示的setNumber,因为“从lambda表达式引用的局部变量必须是最终的或实际上是最终的”(非常有用)。有没有不用线程就可以解决这个问题的方法?完整的代码在下面的pastebin链接中。

private void printNumbers(int[] randomNumbers) {
    int speed = DIFF_TIMES[difficulty.getSelectedIndex()];
    int amount = BASE_AMOUNT + currentScore;
    answerField.setEditable(false);
    scheduleNumbers(randomNumbers, speed, amount);
    currentNumberLab.setText("");
    answerField.setEditable(true);
}

public void scheduleNumbers(int[] randomNumbers, int speed, int amount) {
    int curNumber = 0;
    long initialDelay = 1000;
    final Runnable setNumber = () -> {
        currentNumberLab.setText(Integer.toString(randomNumbers[curNumber]));
        System.out.println("Set to " + randomNumbers[curNumber]);
    };
    final ScheduledFuture<?> setNumberHandle = scheduler.scheduleAtFixedRate(setNumber, initialDelay, speed, MILLISECONDS);
    scheduler.schedule(() -> {
        setNumberHandle.cancel(true);
    }, (speed*amount)+initialDelay, MILLISECONDS);
}


Full code

为清楚起见进行编辑:

我希望能够递增curNumber,因此每次运行setNumber时,它会将currentNumberLab设置为Integer.toString(randomNumbers[curNumber++])

最佳答案

好吧,实际上它是有益的...

尝试以下方法:

public void scheduleNumbers(int[] randomNumbers, int speed, int amount) {
final int curNumber = 0;


它必须是最终的,因为一旦方法完成,您将在线程内失去对局部变量的引用。该方法将完成,但线程可能仍在运行。声明局部变量fi​​nal帮助您解决此问题。

如果要在线程中更新curNumber,请改用AtomicInteger:

public void scheduleNumbers(int[] randomNumbers, int speed, int amount) {
final AtomicInteger curNumber = new AtomicInteger();
long initialDelay = 1000;
final Runnable setNumber = () -> {

    currentNumberLab.setText(Integer.toString(randomNumbers[curNumber.incrementAndGet()]));
    System.out.println("Set to " + randomNumbers[curNumber.get()]);
};

10-07 17:36