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

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

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

//I can't store the word anywhere
public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM3");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

我想这样:

public static void main ( String[] args )
    {
        try
        {
            String data = (new TwoWaySerialComm()).connect("COM3");
            System.out.println("My sensor data: " + data);
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

非常感谢你。

lfapxunr

lfapxunr1#

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

Callable<String> callable = () -> {
        // do stuff
        return "String that your want to return";
    };

    FutureTask<String> task = new FutureTask<>(callable);
    new Thread(task).start();
    System.out.println(task.get());

相关问题