访问内部类中的for循环变量 [英] Accessing a for loop variable inside an inner class

查看:143
本文介绍了访问内部类中的for循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个int数组数组。

I have an array of arrays of int.

DataArray[X][Y]

我想为每个X创建一个线程,它沿着Y迭代。我无法弄清楚如何将适当的X值传递给每个帖子。

I would like to create a thread for each X, which iterates along Y. I cannot figure out how to pass the appropriate X value to each thread.

基本上我希望能够做到

ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < X; i++) {
  threadPool.submit(new Runnable() {
    public void run() {         
      Function_to_run(i);
    }
  });
}

任何帮助将不胜感激

推荐答案

只能在method-local-anonymous-inner-class中捕获 final 值。您需要按如下方式更改代码:

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

         }
     });

这篇关于访问内部类中的for循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆