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

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);
                }
            });
        }
    }
}
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页