Accessing a for loop variable inside an inner class

前端 未结 2 1699
北恋
北恋 2020-12-20 20:12

I have an array of arrays of int.

DataArray[X][Y]

I would like to create a thread for each X, which iterates along Y. I cannot figure out h

相关标签:
2条回答
  • 2020-12-20 20:54

    Only final values can be captured within a method-local-anonymous-inner-class. You need to change your code as follows :

    for (int i = 0; i < X; i++) {
            final int index = i;
            threadPool.submit(new Runnable() {
                 public void run() {
    
                      Function_to_run(index);
    
             }
         });
    
    0 讨论(0)
  • 2020-12-20 20:57

    Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.

    0 讨论(0)
提交回复
热议问题