当前位置: 首页 > 工具软件 > ClassFinal > 使用案例 >

java报错:Variable ‘i‘ is accessed from within inner class, needs to be final or effectively final

阮飞翔
2023-12-01

Variable ‘i’ is accessed from within inner class, needs to be final or effectively final

class Sample{
    public static void main(String[] args) {
        final CountDownLatch count = new CountDownLatch(100);
        //java的线程池
        final ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 100; i++) {
           // int j = i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(i);
                }
            });
        }
    }
}

原因:内部类中使用但未声明的任何局部变量必须在内部类的正文之前明确分配。
解决办法:在for循环内,将i的值重新赋值给另外一个变量 int j = i;

class Sample{
    public static void main(String[] args) {
        final CountDownLatch count = new CountDownLatch(100);
        //java的线程池
        final ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 100; i++) {
            int j = i;
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(j);
                }
            });
        }
    }
}
 类似资料: