简体   繁体   English

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

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

I am new to threads in Java and my question is this.我是 Java 中的线程的新手,我的问题是这个。 If we have an object inside a running thread, and that object's instance variables are being changed inside that thread.如果我们在一个正在运行的线程中有一个 object,并且该对象的实例变量正在该线程中被更改。 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?现在,如果进行另一个 API 调用,那么它想要检查前一个线程中 Object 的已更改实例变量的值,我怎样才能从该线程获取该数据到我当前所在的当前线程? Thank you.谢谢你。

Such object can not be created in one of the threads.这样的 object 不能在其中一个线程中创建。 You said you are using REST API.您说您使用的是 REST API。 So you have some controller or service or some other class that handles your requests.因此,您有一些 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 updates it, so you can get all kinds of unpredictable behavior. So, you have to make your state object thread-safe - a 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 线程安全 - 一个term that means that your state object is aware and supports working with several threads at the same time.这意味着您的 state object 知道并支持同时使用多个线程。 How to make some class thread-safe is huge topic on its own and there are different solutions to that issue.如何使一些 class 线程安全本身就是一个巨大的话题,并且该问题有不同的解决方案。 So read up on "thread-safe"所以请阅读“线程安全”

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

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