多线程中的静态变量 [英] static variables in multithreading

查看:158
本文介绍了多线程中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

静态在多线程中毫无意义.

static makes no sense in Multi-Threading.

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

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.

每个线程都有自己的堆栈

every thread has its own stack

这是正确的陈述. 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.

这篇关于多线程中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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