Why only final variables are allowed inside thread?
Answers
Answered by
2
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 that is how the language is defined. Presumably to keep the variables from being modified within said method in the anonymous inner class. (I do believe it also simplifies the implementation: only the values need to be proxy-copied in to the anonymous type and the original variables need to no longer be kept, as would be required with full closure semantic
final int x = 0;//<----must be final... private class myRun implements Runnable { @Override public void run() { x++;// } }
Because that is how the language is defined. Presumably to keep the variables from being modified within said method in the anonymous inner class. (I do believe it also simplifies the implementation: only the values need to be proxy-copied in to the anonymous type and the original variables need to no longer be kept, as would be required with full closure semantic
Similar questions
English,
7 months ago
Science,
7 months ago
Business Studies,
1 year ago
Physics,
1 year ago
English,
1 year ago