为什么传递给runnable的变量需要是最终的? [英] Why do variables passed to runnable need to be final?
问题描述
如果我有一个变量 int x = 1
,比如说,我在主线程中声明了一个runnable,我想把x传递给runnable的 run()
方法,必须声明 final
。为什么?
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:
public void count()
{
int x;
new Thread(new Runnable()
{
public void run()
{
while(x < 100)
{
x++;
try
{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}).start();
// do some more code...
for(x = 0;x < 5;x++)
for(int y = 0;y < 10;y++)
System.out.println(myArrayElement[x][y]);
}
这是一个粗略的例子,但你可以看到很多无法解释的错误可以在哪里发生。这就是变量必须是最终的原因。以下是针对上述问题的简单修复:
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:
public void count()
{
int x;
final int w = x;
new Thread(new Runnable()
{
public void run()
{
int z = w;
while(z < 100)
{
z++;
try
{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}).start();
// do some more code...
for(x = 0;x < 5;x++)
for(int y = 0;y < 10;y++)
System.out.println(myArrayElement[x][y]);
}
如果你想要更全面的解释,它有点像同步。 Java希望阻止您从多个线程引用一个Object。这里有一点关于同步:
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:
- http://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
希望这有帮助!
这篇关于为什么传递给runnable的变量需要是最终的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!