小编典典

多线程中的静态变量

java

I found that declaring a variable as static makes no sense多线程中
。我认为这是因为every thread has its own stack。这是唯一原因吗?

我知道static variables should be used within synchronized block。但为什么?


阅读 358

收藏
2020-11-16

共1个答案

小编典典

在多线程中,static没有意义。

恐怕你在做相反的陈述
。静态变量是一种共享资源,可用于在不同线程之间交换某些信息。而且,在访问这种共享资源时我们需要小心。因此,我们需要确保在多线程环境中对静态变量的访问是同步的。

每个线程都有自己的堆栈

这是正确的说法。Each thread has its own stack but they share the process heap.堆栈仅保存局部变量,而不保存堆中的变量。静态变量存储在PermGen堆的部分中,因此应妥善保护对它们的访问。

2020-11-16