How can I get the String from a running Thread?

250 Views Asked by At

I am using the RXTX API to get data from a sensor. https://web.archive.org/web/20200530110106/rxtx.qbang.org/wiki/index.php/Event_Based_Two_Way_Communication

I copy-pasted the Code and it works so far. How do I store the received Data inside a String?

//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();
        }
    }

I want to have it this way:

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();
        }
    }

Thank you very much.

1

There are 1 best solutions below

0
Navin M On

If you need to return anything or throw an Exception from a new Thread, you need to create a Thread using java.util.concurrent.Callable interface and implement call() method.

It is similar to Runnable. However, the process of starting the Thread is slightly different as the Thread class doesn't have any constructor that accepts Callable object.

    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());