{"title":"for(int i=1;i<=13;i++) { //\t\tint temp = i; \t\t\tRunnable r = new Runnable() { \t\t\t\tpublic void run() { \t\t\t\t\tSystem.out.println(Thread.currentThread().getName()+"--"+i); \t\t\t\t} \t\t\t}; \t\t\tpool.execute(r); \t\t} 为什么i报错","description":"在此代码中,i报错是因为在匿名内部类中使用了外部变量i,而匿名内部类中的变量必须是final或者是事实上final的(即不能修改的)。\n\n解决这个问题的方法是将变量i声明为final,或者将变量i复制给一个final变量temp,并在匿名内部类中使用temp来代替i。\n\n修正后的代码如下所示:\n\n\nfor(int i=1; i<=13; i++) {\n final int temp = i; \n Runnable r = new Runnable() { \n public void run() { \n System.out.println(Thread.currentThread().getName()+"--"+temp); \n } \n }; \n pool.execute(r); \n}\n\n\n这样就不会报错了。"}

Java 匿名内部类中使用外部变量i报错的解决方法

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

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