Hi,
Why is the Elvis elvis definition has to be final to be used inside the Thread run() method?
Elvis elvis = Elvis.INSTANCE; // ----> should be final Elvis elvis = Elvis.INSTANCE
elvis.sing(4);
Thread t1 = new Thread(
new Runnable() {
@Override
public void run() {
elvis.sing(6); // --------> elvis has to be final to compile
}
}
);
public enum Elvis {
INSTANCE(2);
Elvis() {
this.x = new AtomicInteger(0);
}
Elvis(int x){
this.x = new AtomicInteger(x);
}
private AtomicInteger x = new AtomicInteger(0);
public int getX() { return x.get(); }
public void setX(int x) {this.x = new AtomicInteger(x);}
public void sing(int x) {
this.x = new AtomicInteger(x);
System.out.println("Elvis singing.." + x);
}
}