为什么局部变量在 Java 中是线程安全的 [英] Why are local variables thread safe in Java

查看:40
本文介绍了为什么局部变量在 Java 中是线程安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Java 中的多线程,我遇到了这个

I was reading multi-threading in Java and I come across this

局部变量在 Java 中是线程安全的.

Local variables are thread safe in Java.

从那时起我一直在思考局部变量如何/为什么是线程安全的.

Since then I have been thinking How/Why local variables are thread safe.

谁能告诉我.

推荐答案

当您创建一个线程时,它将创建自己的堆栈.两个线程将有两个堆栈,一个线程永远不会与其他线程共享其堆栈.

When you create a thread it will have its own stack created. Two threads will have two stacks and one thread never shares its stack with other thread.

程序中定义的所有局部变量都将在堆栈中分配内存(正如 Jatin 所评论的,这里的内存意味着,对象的引用值和原始类型的值)(线程的每个方法调用都会自行创建一个堆栈帧堆).一旦该线程完成方法执行,堆栈帧将被移除.

All local variables defined in your program will be allocated memory in stack (As Jatin commented, memory here means, reference-value for objects and value for primitive types) (Each method call by a thread creates a stack frame on its own stack). As soon as method execution is completed by this thread, stack frame will be removed.

斯坦福大学教授的精彩讲座可能会有所帮助你在理解这个概念.

There is great lecture by Stanford professor in youtube which may help you in understanding this concept.

这篇关于为什么局部变量在 Java 中是线程安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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