简体   繁体   English

如何从另一个线程或进程中提取数据(Android / Java)

[英]How do I pull data from another thread or process (Android/Java)

I know of concepts that allow inter-process communication. 我知道允许进程间通信的概念。 My program needs to launch a second thread. 我的程序需要启动第二个线程。 I know how to pass or "push" data from one thread to another from Java/Android, but I have not seen a lot of information regarding "pulling" data. 我知道如何从Java / Android将数据从一个线程传递或“推”到另一个线程,但是我还没有看到很多有关“拉”数据的信息。 The child thread needs to grab data on the parent thread every so often. 子线程需要经常在父线程上获取数据。 How is this done? 怎么做?

Since threads share memory you can just use a thread safe data structure. 由于线程共享内存,因此您只能使用线程安全的数据结构。 Refer to java.util.concurrent for some. 请参考java.util.concurrent。 Everything in that package is designed for multi threaded situations. 该软件包中的所有内容都是针对多线程情况而设计的。

In your case you might want to use a LinkedBlockingQueue. 在您的情况下,您可能要使用LinkedBlockingQueue。 This way the parent thread can put things into the queue, and the child thread can grab it off whenever it likes. 这样,父线程可以将事物放入队列,而子线程可以在需要时将其抓取。 It also allows the child thread to block if the Queue is empty. 如果队列为空,它还允许子线程阻塞。

You may be confusing threads and data. 您可能会混淆线程和数据。 Threads are lines of code execution which may operate on some data but they are not data themselves and they do not contain data. 线程是代码执行的行,可以对某些数据进行操作,但它们本身不是数据,并且不包含数据。 Data is contained in memory and threads are executed by CPU (or vm or whatever level you choose). 数据包含在内存中,线程由CPU(或vm或您选择的任何级别)执行。

You access data in the same way whether it is done in threads or not. 无论数据是否在线程中完成,您都可以用相同的方式访问数据。 That is you use variables or object fields etc. But with threads you need to make sure that there are no race conditions which happen when threads concurrently access the same data. 那就是您使用变量或对象字段等。但是对于线程,您需要确保在线程并发访问相同数据时不发生竞争条件。

To summarize, if you have an object that has some method executed by thread, you can still get data from this object in regular way as long as you make sure that only one thread does it at the same time. 总而言之,如果您有一个由线程执行某些方法的对象,则只要确保同时只有一个线程可以执行此操作,就仍可以常规方式从该对象获取数据。

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

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