我想像这样在多个线程之间共享一个变量:
boolean flag = true;
T1 main = new T1();
T2 help = new T2();
main.start();
help.start();
我想在主线程和帮助线程之间共享 flag
,这是我创建的两个不同的 Java 类。有什么办法吗?谢谢!
最佳答案
T1
和T2
都可以引用包含该变量的类。
然后你可以让这个变量volatile,这意味着
对该变量的更改在两个线程中立即可见。
参见 this article了解更多信息。
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
与更复杂的共享状态方式的优缺点。
关于java - 在多个不同线程之间共享一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13582395/