我声明了一个twoWaySerialComm对象来配置端口连接。在twoWaySerialComm类中,我创建了一个线程来读取名为' SerialReader'的类中的传入串行数据。如何从主线程' twoWaySerialComm'?
访问串行数据我已将传入的串行数据读入' hex' ' SerialReader'中的字符串一个while循环中的类。我能够在while循环中打印传入的数据,但是我无法访问这个' hex' ' twoWaySerialComm'中的字符串类。为什么我无法访问' hex' while循环外的字符串?如何才能做到这一点?
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author asanka
*/
public class TwoWaySerialComm {
private static TwoWaySerialComm twoWaySerialComm;
String read;
private TwoWaySerialComm() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException {
String portName = "/dev/ttyUSB0";
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
SerialReader reader;
(new Thread(reader = new SerialReader(in))).start();
read = reader.readHex();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public static TwoWaySerialComm getTwoWaySerialComm() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException {
if (twoWaySerialComm == null) {
twoWaySerialComm = new TwoWaySerialComm();
}
return twoWaySerialComm;
}
public String data() {
return read;
}
/**
*
*/
public static class SerialReader implements Runnable {
String hex;
InputStream in;
public SerialReader(InputStream in) {
this.in = in;
}
public void run() {
byte[] buffer = new byte[1024];
int len;
try {
while ((len = this.in.read(buffer)) > -1) {
hex = new String(buffer, 0, len).replaceAll("\\s", "");
Thread.sleep(1000);
System.out.println(hex);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ex) {
Logger.getLogger(TwoWaySerialComm.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String readHex() {
return hex;
}
}
/**
*
*/
public static class SerialWriter implements Runnable {
OutputStream out;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
try {
int c = 0;
while ((c = System.in.read()) > -1) {
this.out.write(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:0)
据我所知,您正在另一个Thread中运行读取操作。在调用readHex()方法时,该Thread可能尚未填充hex字段。
首先需要在新线程上调用join(),以确保它已完成。 或者使用java.util.concurrent包中的CompletableFuture。