如何从正在运行的线程中获取字符串?

zpf6vheq  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(538)

我正在使用rxtxapi从传感器获取数据。https://web.archive.org/web/20200530110106/rxtx.qbang.org/wiki/index.php/event_based_two_way_communication
我复制粘贴的代码,它的作品迄今为止。如何将接收到的数据存储在字符串中?

  1. //I can't store the word anywhere
  2. public static void main ( String[] args )
  3. {
  4. try
  5. {
  6. (new TwoWaySerialComm()).connect("COM3");
  7. }
  8. catch ( Exception e )
  9. {
  10. // TODO Auto-generated catch block
  11. e.printStackTrace();
  12. }
  13. }

我想这样:

  1. public static void main ( String[] args )
  2. {
  3. try
  4. {
  5. String data = (new TwoWaySerialComm()).connect("COM3");
  6. System.out.println("My sensor data: " + data);
  7. }
  8. catch ( Exception e )
  9. {
  10. // TODO Auto-generated catch block
  11. e.printStackTrace();
  12. }
  13. }

非常感谢你。

lfapxunr

lfapxunr1#

如果需要从新线程返回任何内容或抛出异常,则需要使用java.util.concurrent.callable接口创建线程并实现call()方法。
它类似于runnable。但是,启动线程的过程略有不同,因为thread类没有任何接受可调用对象的构造函数。

  1. Callable<String> callable = () -> {
  2. // do stuff
  3. return "String that your want to return";
  4. };
  5. FutureTask<String> task = new FutureTask<>(callable);
  6. new Thread(task).start();
  7. System.out.println(task.get());

相关问题