I have came across many situation where I needed to pass value to an other thread and I founded out that I could do it this way, but I have been wondering how is it working ?
public void method() {
final EventHandler handle = someReference;
Thread thread = new Thread() {
public void run() {
handle.onEvent();
}
};
thread.start();
}
Edit: Just realise my question wasn't exactly pointing toward what I wanted to know. It's more "how" it works rather then "why".
Here's a longer explanation of HOW it works: http://techtracer.com/2008/04/14/mystery-of-accessibility-in-local-inner-classes/
No method can access local variables of other methods. This includes methods of anonymous classes as the one in your example. That is, the run
method in the anonymous Thread class, can not access the local variable of method()
.
Writing final
in front of the local variable is a way for you as a programmer to let the compiler know that the variable actually can be treated as a value. Since this variable (read value!) will not change, it is "ok" to access it in other methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With