Sharing a variable between multiple different threads(在多个不同线程之间共享一个变量)
问题描述
我想像这样在多个线程之间共享一个变量:
I want to share a variable between multiple threads like this:
boolean flag = true;
T1 main = new T1();
T2 help = new T2();
main.start();
help.start();
我想在主线程和帮助线程之间共享 flag
,这是我创建的两个不同的 Java 类.有什么办法吗?谢谢!
I'd like to share flag
between main and help thread where these are two different Java classes I've created. Is any way to do this? Thanks!
推荐答案
T1
和 T2
都可以引用包含该变量的类.
然后,您可以使这个变量 volatile,这意味着
对该变量的更改在两个线程中立即可见.
Both T1
and T2
can refer to a class containing this variable.
You can then make this variable volatile, and this means that
Changes to that variable are immediately visible in both threads.
有关详细信息,请参阅这篇文章.
See this article for more info.
易失性变量共享同步但没有原子性特征.这意味着线程将自动查看 volatile 变量的最新值.它们可以用来提供线程安全,但只能在非常受限的案例集:那些不施加约束的案例多个变量或变量的当前值与其未来的价值.
Volatile variables share the visibility features of synchronized but none of the atomicity features. This means that threads will automatically see the most up-to-date value for volatile variables. They can be used to provide thread safety, but only in a very restricted set of cases: those that do not impose constraints between multiple variables or between a variable's current value and its future values.
并注意使用 volatile
与更复杂的共享状态方式的优缺点.
And note the pros/cons of using volatile
vs more complex means of sharing state.
这篇关于在多个不同线程之间共享一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在多个不同线程之间共享一个变量
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01