Why are only final variables accessible in anonymous class?
java thread accessing outer object before it's created
public class A { private final int a; public A() { Thread t = new Thread(new Runnable() { @Override public void run() { System.out.println("----"); System.out.println(a); } }); t.start(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } a = 9; System.out.println("===="); System.out.println(a); }
输出:
---- 0 ==== 9