Final enum in Thread's run() method
Posted
by portoalet
on Stack Overflow
See other posts from Stack Overflow
or by portoalet
Published on 2010-03-28T12:05:39Z
Indexed on
2010/03/28
12:13 UTC
Read the original article
Hit count: 241
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);
}
}
© Stack Overflow or respective owner