在多个不同线程之间共享变量 [英] Sharing a variable between multiple different threads

查看:104
本文介绍了在多个不同线程之间共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在多个线程之间共享一个变量,如下所示:

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 之间main和help线程,这些是我创建的两个不同的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 immeditately visible in both threads.

请参阅本文了解更多信息。


易失性变量共享synchronized的可见性功能,但
没有原子性功能。这意味着线程将
自动查看volatile变量的最新值。
它们可用于提供线程安全性,但仅限于非常b $ b的限制案例:那些不在
多个变量之间或变量的当前值与其$ b之间施加约束的情况$ b未来价值。

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.

这篇关于在多个不同线程之间共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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