简体   繁体   English

在java中实时将IO Process的值传递给另一个类

[英]passing values of IO Process to another class in real time in java

I have a basic question for which I need a some clarification in it's use. 我有一个基本问题,我需要对其进行一些澄清。
So if I have one class in Java say IOReadWrite.java , where I do some IO read/write. 所以如果我在Java中有一个类说IOReadWrite.java ,我在那里做一些IO读/写。 So that it may have an always connected loop something like: 所以它可能有一个总是连接的循环,如:

while ((line = stream.readLine()) != null){
     //incoming data
}  

Now I have another class, call it FrontEnd.java where I am supposed to display the results coming in real time from IOReadWrite.java Class. 现在我有另一个类,称之为FrontEnd.java ,我应该从IOReadWrite.java类实时显示结果。 Normally what is happening is that if I call the method of IO class, I can not get result unless the whole IO Operation is finished and I have to wait. 通常情况下,如果我调用IO类的方法,除非整个IO操作完成并且我必须等待,否则我无法获得结果。

However what I want is to be able to get those results in real time, so that as soon as there is something on input Stream, I can get it in my FrontEnd Class to do whatever I want to do with it. 然而我想要的是能够实时获得这些结果,这样只要输入Stream上有东西,我就可以在我的FrontEnd类中得到它来做我想做的任何事情。

One idea I have come up with is using a static String variable in IOReadWrite.java and write a method which simply returns the value of this variable and I can poll this function from main class. 我想到的一个想法是在IOReadWrite.java中使用静态String变量并编写一个方法,它只返回此变量的值,我可以从主类中轮询此函数。 But I'm pretty sure this is a very bad approach. 但我很确定这是一个非常糟糕的方法。

Can you suggest what is the proper way of getting such information in real time? 您能否建议实时获取此类信息的正确方法是什么?

You can do this 你可以这样做

FrontEnd frontEnd = 
while ((line = stream.readLine()) != null){
     //incoming data

     // notify immediately.
     frontEnd.displayLine(line);
}

What displayLine does depends on your implementation of that class. displayLine的作用取决于您对该类的实现。 Can you give any more details of that the class does with the information? 你能否提供一下班级对这些信息的更多细节?

Something it could do is 它可以做的事情是

private final BlockingQueue<String> linesQueue = ...

public void displayLine(String line) {
     linesQueue.add(line);
}

// somewhere else, in another thread.
String line = linesQueue.take(); // wait for a line.

String line = linesQueue.poll(); // get the next or null

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

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