简体   繁体   English

在同步块中声明了不可访问的变量-Java

[英]Inaccessible variable declared in synchronized block - Java

This piece of code will not compile: 这段代码将无法编译:

    synchronized( obj ) {
        Object a = new Object()
    }

    System.out.println( a.toString() );

Yet I don't know why.. My understanding was that a synchronized block was always eventually executed, so I would expect code following the synchronized block to be aware of any new declared variables. 但是我不知道为什么。.我的理解是,同步块总是最终执行,所以我希望同步块后面的代码知道任何新声明的变量。 Where am I wrong? 我哪里错了?

It's not the synchronization, it's the {} symbols. 这不是同步,而是{}符号。 They define a scope, no matter whether there's an if , for , synchronized , or even nothing at the beginning of them. 它们定义了一个范围,无论它们的开头是否存在ifforsynchronized甚至什么都没有。 So the a goes out of scope once the block finishes, because it was declared within it. 因此,一旦块完成, a就会超出范围,因为它是在其中声明的。 (Also there's a missing semicolon at the end of the Object a declaration but I suspect you just forgot to copy that.) (此外, Object a声明的末尾缺少分号,但我怀疑您只是忘记复制该分号。)

Variable scope is not determined by what gets executed. 变量范围不取决于执行的内容。 Variables are visible only inside the block they are declared in. You probably want to do something like this: 变量仅在声明它们的块内部可见。您可能想要执行以下操作:

Object a;
synchronized( obj ) {
    a = new Object()
}

System.out.println( a.toString() );

Variables defined inside a block don't live outside the block. 块内定义的变量不在该块外。

From the Java Language Specification : 根据Java语言规范

The scope of a local variable declaration in a block (§14.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement. 块中的局部变量声明的范围(第14.2节)是该声明出现在该块的其余部分,从其自身的初始化程序(第14.4节)开始,并在该局部变量声明语句的右侧包括其他任何声明符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM