java线程等待comport上的输入阻塞其他线程

时间:2013-11-05 13:48:48

标签: java multithreading

我有一个启动两个线程的主程序。首先我只有这个线程,在while(true)中执行以下命令:

loopCounter++;              
outputStream.write(pollBuf);
readResponse();
Thread.sleep(200);
outputStream.write(statusBuf);
readResponse();
logger.info("status executed");

问题是,当第二个readResponse没有返回时,因为听取comport的设备根本没有回答我被卡住了,给出机器状态的显示器仍然显示“正在运行”而不是软件错误或类似的东西。 所以我需要知道这个线程何时被卡住,因此我添加了另一个线程,现在在另一个线程之前的主程序中创建并启动,第二个线程的run()方法的while(true)内的代码:

public class StatusThread implements Runnable {
  static Logger logger = Logger.getLogger(StatusThread.class);

  private Nv10ToVcdm mainProgram;

  public void initialize(Nv10ToVcdm mProgram, boolean acceptBills) {
    mainProgram = mProgram;
  }

  public void run() {
    int loopCounter = mainProgram.getLoopCounter();
    while (true) {
      try {
        Thread.sleep(1000);
        int currentLoopCounter = mainProgram.getLoopCounter();
        if (loopCounter != currentLoopCounter) {
          loopCounter = currentLoopCounter;
        } else {
          mainProgram.writeToDisplay("SOFTWARE", "ERROR");
        }
      } catch (InterruptedException ie) {
        logger.error("Interrupted exception: " + ie.getMessage());
        mainProgram.errorOnDisplay();
      }
    }
  }
}

可悲的是,第一个线程在听取comport时没有释放它在cpu上的声明,所以第二个线程没有得到任何CPU时间。那么:当侦听com端口的线程挂起时,如何在显示器上显示错误?

挂起的readResponse方法,afaik挂起“byte firstByte =(byte)inputStream.read();”因为没有什么可读的:

private void readResponse() {
    byte[] bufferLeft = new byte[4];
    byte[] bufferRight = new byte[2];
    byte size = 0;
    boolean responseFound = false;

    try {
      while(!responseFound) {
        byte firstByte = (byte) inputStream.read();
        if (firstByte == -1) {
          logger.error("first byte of response is -1");
          mainProgram.errorOnDisplay();
          break;
        }
        for (int i = 0; i < 4; i++) {
          bufferLeft[i] = (byte) inputStream.read();
        }
        size = bufferLeft[0];
        if (size > 0) {
          bufferRight =  new byte[size];
          int i2 = 0;
          while (i2 < size) {
            bufferRight[i2] = (byte) inputStream.read();
            i2++;
          }
        }

        if (firstByte == 1 && bufferLeft[1] == 40) {
          responseFound = true;
        }
      }

      if (size == 11) {
        // some code
      }
    } catch(IOException ioe) {
      logger.error("IO Exception in readResponse: " + ioe.getMessage());
      mainProgram.errorOnDisplay();
    }
}

编辑(为第二个线程添加完整代码&amp; readResponse方法)

输入流初始化如下:

serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
inputStream = serialPort.getInputStream(); 

1 个答案:

答案 0 :(得分:1)

您在阅读之前是否尝试检查数据可用性?

类似的东西:

if (inputStream.available() > 0) {
  // do your read
} else {
  // wait for some time and retry or trow an error
}