繁体   English   中英

如何从另一个线程访问线程中的数据

[英]How to access data in a thread from another thread

我是 Java 中的线程的新手,我的问题是这个。 如果我们在一个正在运行的线程中有一个 object,并且该对象的实例变量正在该线程中被更改。 现在,如果进行另一个 API 调用,那么它想要检查前一个线程中 Object 的已更改实例变量的值,我怎样才能从该线程获取该数据到我当前所在的当前线程? 谢谢你。

这样的 object 不能在其中一个线程中创建。 您说您使用的是 REST API。 因此,您有一些 controller 或服务或其他一些 class 来处理您的请求。 In that service (or some other class that is accessible from your service you need to have some class as a property with some state that could be updated and read. So, this object scope survives any thread and any request. So, when your request comes you can access your state object and update it or read the current state. But you have to understand that now several threads can access your state object at the same time and situation can happen when one thread tries to read the state just as another one更新它,所以你可以获得各种不可预知的行为。所以,你必须让你的 state object 线程安全 - 一个这意味着您的 state object 知道并支持同时使用多个线程。 如何使一些 class 线程安全本身就是一个巨大的话题,并且该问题有不同的解决方案。 所以请阅读“线程安全”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM