中的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。但为什么?

最佳答案



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



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

09-10 04:52
查看更多