If I have a variable int x = 1, say, and I declare a runnable in the main thread, and I want to pass x to the runnable’s run() method, it must be declared final. Why?
final int x = 0;//<----must be final...
private class myRun implements Runnable {
@Override
public void run() {
x++;//
}
}
Because if they are able to be changed, it could cause a lot of problems, consider this:
This is a rough example but you can see where a lot of unexplained errors could occur. This is why the variables must be final. Here is a simple fix for the problem above:
If you want a more full explanation, it is sort of like synchronized. Java wants to prevent you from referencing one Object from multiple Threads. Here is a little bit about synchronization:
Hope this helped!