问题描述
I found that declaring a variable as static makes no sense
.我认为这是由于every thread has its own stack
引起的.这是唯一的原因吗?
I found that declaring a variable as static makes no sense
in Multi-Threading. I assume that, this is because of every thread has its own stack
. Is this the only reason?
我知道static variables should be used within synchronized block
.但是为什么呢?
I know that static variables should be used within synchronized block
. but why?
推荐答案
恐怕您正在做出相反的声明.静态变量是一种共享资源,可用于在不同线程之间交换某些信息.而且,在访问这种共享资源时,我们需要小心.因此,我们需要确保多线程环境中对静态变量的访问是同步的.
Im afraid you are making the reverse statement. Static variable is a shared resource, which can be used to exchange some information among different threads. And we need to be careful while accessing such a shared resource. Hence, we need to make sure that the access to static variables in multi-threaded environment is synchronized.
这是正确的陈述. Each thread has its own stack but they share the process heap.
堆栈仅保存局部变量,而不保存堆上的变量.静态变量存储在堆的PermGen
部分中,因此应妥善保护对它们的访问.
This is a correct statement. Each thread has its own stack but they share the process heap.
Stack holds only the local variables and not the variables on the heap. Static variables are stored in the PermGen
section of the heap and hence the access to them should be well guarded.
这篇关于多线程中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!