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

发布于 2025-02-12 09:01:40 字数 130 浏览 0 评论 0原文

我是Java中线程的新手,我的问题是。如果我们在运行线程中有一个对象,并且该对象的实例变量在该线程中正在更改。现在,如果进行了另一个API调用,则希望检查上一个线程中对象的更改实例变量的值,我该如何将数据从该线程中获取到我当前的当前线程中?谢谢。

I am new to threads in Java and my question is this. If we have an object inside a running thread, and that object's instance variables are being changed inside that thread. Now, if another API call is made, that wants to check the values of the changed instance variables of the Object that was in the previous thread, how can I get that data from that thread into the current thread that I'm in currently? Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落在眉间の轻吻 2025-02-19 09:01:40

不能在其中一个线程中创建此对象。您说您正在使用REST API。因此,您有一些控制器或服务或其他处理您请求的课程。在该服务中(或其他可以从您的服务访问的其他类,您需要将某些类作为一个可以更新和阅读的状态的属性。因此,此对象范围可以生存任何线程和任何请求。因此,当您的请求时来了,您可以访问状态对象并进行更新或读取当前状态。更新它,因此您可以得到各种不可预测的行为,您必须使您的状态对象线程安全 - 这意味着您的状态对象知道并支持与多个线程一起工作。自己的解决方案有不同的解决方案。

Such object can not be created in one of the threads. You said you are using REST API. So you have some controller or service or some other class that handles your requests. 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 updates it, so you can get all kinds of unpredictable behavior. So, you have to make your state object thread-safe - a term that means that your state object is aware and supports working with several threads at the same time. How to make some class thread-safe is huge topic on its own and there are different solutions to that issue. So read up on "thread-safe"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文