简体   繁体   English

循环问题

[英]While-loop issues

I'm reading data from a serial port inside a while-loop as follows: 我正在从while循环内的串行端口读取数据,如下所示:

while((len = this.getIn().read(buffer)) > 0) {
    data = new String(buffer, 0, len);
    System.out.println("data len " + len);
    handleModemresponse(data);
}

but, while reading the data from the stream starts, the main AWT window, which has a disconnect button, is not getting any listeners (the whole window not getting listeners). 但是,当从流中读取数据开始时,具有断开按钮的主AWT窗口没有获取任何侦听器(整个窗口没有获取侦听器)。 It only listens when transfer completes, ie, outside the while-loop. 它仅在传输完成时(即在while循环之外)进行侦听。

I want my AWT window to listen for my actions when it is in the while-loop also. 我希望我的AWT窗口在while循环中时也要监听我的操作。

Any ideas how I can achieve this? 有什么想法可以实现这一目标吗?

Create a new Thread for the read action. 为读取操作创建一个新线程。

public class LongProcess implements Runnable {
  public void startProcess() {
    Thread t = new Thread(this);
    t.start();
  }

      public void run() {
// Define inputstream here
        while((len = inputStream.read(buffer)) > 0) {
         data = new String(buffer, 0, len);
         System.out.println("data len " + len);
         handleModemresponse(data);
        }
      }
    }

EDIT (after comment Tom Hawtin - tackline): 编辑 (Tom Hawtin评论后-大头贴):

SwingUtilities.invokeLater(new LongProcess ());

It looks like you have everything in one thread - thus while your working method is in progress, your GUI seems blocked and does not respond to any actions until the loop ends. 似乎您将所有内容都放在一个线程中-因此,当您的工作方法正在进行时,您的GUI似乎被阻塞,并且直到循环结束才响应任何操作。

You have to separate your GUI attendance in one thread and your working method in another. 您必须在一个线程中将GUI出席人数与在另一个线程中的工作方法分开。

The read method you are calling is blocking. 您正在调用的read方法正在阻止。 You need to move it in a different thread in order for your listeners to keep working. 您需要将其移动到其他线程中,以使您的听众继续工作。

我怀疑您应该将此while循环推入一个单独的线程中,以免在传输过程中占用AWT线程。

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

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