java中的最终变量和同步块 [英] Final variable and synchronized block in java

查看:195
本文介绍了java中的最终变量和同步块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的最终变量是什么?例如:如果我在函数中写 final int temp; ,那么final关键字的含义是什么?

另外,我什么时候想要使用final变量(作为类变量和函数变量)?

为什么同步块中的变量必须声明为final?

What is a final variable in Java? For example: if I write final int temp; in function what is the meaning of the final keyword?
Also, when would I want to use final variable (both as a class variable and as a function variable)?
Why must variables in a synchronized block be declared final?

推荐答案

基本上它只是意味着你无法改变价值。对于实例变量,您必须在构造函数(或使用变量初始值设定项)中分配一次(并且仅一次)任何最终变量。同步是一个非常正交的概念。

Basically it just means you can't change the value. For instance variables, you have to assign any final variables once (and only once) in the constructor (or with a variable initializer). Synchronization is a pretty orthogonal concept.

local 变量设为final的主要原因是你可以在匿名内部类中使用它。 ..这与处于同步块中没有任何关系。

The primary reason for making a local variable final is so you can use it in an anonymous inner class... this has nothing to do with being in a synchronized block.

最终变量 对于不可变类非常有用 - 不可否认 - 并且不变性使生命变得有效在多线程环境中更容易 - 但这是我能想到的两者之间唯一的关系...

Final variables are useful for immutable classes, admittedly - and immutability makes life easier in a multi-threaded environment - but that's the only relationship between the two that I can think of...

编辑:Wildwezyr的评论在不改变方面是有意义的要同步的变量 。由于他给出的原因,这将是危险的。这就是同步块中的变量的含义吗?

Wildwezyr's comment makes sense in terms of not changing the variable on which you are synchronizing. That would be dangerous, for the reasons he's given. Is that what you meant by "variable in synchronized block"?

这篇关于java中的最终变量和同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆