Java中的Volatile Vs Static [英] Volatile Vs Static in java

查看:119
本文介绍了Java中的Volatile Vs Static的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否正确的说, static 表示所有对象的值的一个副本, volatile 表示所有线程的值的一个副本?

Is it correct to say that static means one copy of the value for all objects and volatile means one copy of the value for all threads?

无论如何一个 static 变量值也将是所有线程的一个值,那么为什么我们应该去

Anyway a static variable value is also going to be one value for all threads, then why should we go for volatile?

推荐答案

静态和易失性之间的区别:

Difference Between Static and Volatile :

strong>静态变量:如果两个线程(假设 t1 t2 )访问同一对象,更新被声明为静态的变量,则它意味着 t1 t2 可以创建自己的同一对象的本地副本(包括静态变量)在它们各自的缓存中,因此 t1 对其本地缓存中的静态变量进行的更新不会反映在 t2的静态变量

Static Variable: If two Threads(suppose t1 and t2) are accessing the same object and updating a variable which is declared as static then it means t1 and t2 can make their own local copy of the same object(including static variables) in their respective cache, so update made by t1 to the static variable in its local cache wont reflect in the static variable for t2 cache .

静态变量用于对象的上下文中,其中一个对象进行的更新将反映在所有同一类的其他对象,但不在Thread 的上下文中,其中一个线程的更新将静态变量将立即反映到所有线程(在它们的本地缓存中)。

Static variables are used in the context of Object where update made by one object would reflect in all the other objects of the same class but not in the context of Thread where update of one thread to the static variable will reflect the changes immediately to all the threads (in their local cache).

变量变量:如果两个线程(假设 t1 t2 )访问同一个对象并更新一个被声明为volatile的变量,那么它意味着 t1 t2 可以自己创建本地缓存对象,除了被声明为volatile的变量。因此,volatile变量将只有一个主副本,它将被不同的线程更新,并且由一个线程对volatile变量进行的更新将立即反映到另一个线程。

Volatile variable: If two Threads(suppose t1 and t2) are accessing the same object and updating a variable which is declared as volatile then it means t1 and t2 can make their own local cache of the Object except the variable which is declared as a volatile . So the volatile variable will have only one main copy which will be updated by different threads and update made by one thread to the volatile variable will immediately reflect to the other Thread.

这篇关于Java中的Volatile Vs Static的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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