在此代码中,i报错是因为在匿名内部类中使用了外部变量i,而匿名内部类中的变量必须是final或者是事实上final的(即不能修改的)。

解决这个问题的方法是将变量i声明为final,或者将变量i复制给一个final变量temp,并在匿名内部类中使用temp来代替i。

修正后的代码如下所示:

for(int i=1; i<=13; i++) {
    final int temp = i;
    Runnable r = new Runnable() {
        public void run() {
            System.out.println(Thread.currentThread().getName()+"--"+temp);
        }
    };
    pool.execute(r);
}

这样就不会报错了。

forint i=1;i=13;i++ 			int temp = i; 			Runnable r = new Runnable 				public void run 					SystemoutprintlnThreadcurrentThreadgetName+--+i; 				 			; 			poolexecuter; 		 为什么i报错

原文地址: https://www.cveoy.top/t/topic/ihrD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录