在另一个 class 中传递非最终整数

Passing non-final integer in another class

我有这个问题:我想使用 for 循环一次执行多个线程。我想将变量 "i" 传递给线程中的一个方法。但是出现错误,我无法将非最终变量 "i" 传递给另一个 class。我该如何解决?这是我的代码:

for (int i = 0; i < 4; i++) { // 4 THREADS AT ONCE
  thread[i] = new Thread() {
    public void run() {
      randomMethod(i); // ERROR HERE
    }
  };
  thread[i].start();
}

试试这个

for (int i = 0; i < 4; i++) { // 4 THREADS AT ONCE
  final int temp=i;
  thread[i] = new Thread() {
    public void run() {
      randomMethod(temp); // ERROR HERE
    }
  };
  thread[i].start();
}

您可以使用类似于以下的代码:

public class MyRunnable implements Runnable {
    private int i;

    public MyRunnable(int i) {
        this.i = i;
    }

    public void run() {
        randomMethod(i); 
    }
}

// In another class
...
for (int i = 0; i < 4; i++) { // 4 THREADS AT ONCE
    thread[i] = new Thread(new MyRunnable(i));
}
thread[i].start();
...

如前所述,有很多方法可以解决这个问题,但重要的是要知道为什么会出现错误。

这是因为Java将匿名class中使用的final变量复制到这个class。如果此变量不是最终的,则无法保证您将始终拥有此变量的正确(最新)版本。所以,你不能在匿名 class 声明中使用任何非 final 局部变量(因为 Java 8 个有效的 final 就足够了)。