Search code examples
javamultithreadingfor-loopintegerfinal

Passing non-final integer in another class


I have this problem: I want to execute multiple threads at once, using a for-loop. I want to pass the variable "i" to a method in the thread. But there is an error occuring, I cannot pass a non-final variable "i" into another class. How can I fix that? This is my code:

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();
}

Solution

  • Try this

    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();
    }