简体   繁体   English

从线程java返回值

[英]Return value from thread java

I am trying to receive serial data from Arduino and i want to store the value in a variable how can i do it ? 我正在尝试从Arduino接收串行数据,我想将值存储在变量中,我该怎么办? I tried the code below but it is not storing the value of string in the array element t[0] 我尝试了以下代码,但未将字符串的值存储在数组元素t [0]中

or is there a way to store reading from input stream ? 还是有一种方法可以存储输入流中的读数?

final String[] t = new String[1];
t[0]="0";
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];

Thread thread  = new Thread(new Runnable()
{
    public void run()
    {
        while(!Thread.currentThread().isInterrupted() && !stopThread)
        {
            try
            {
                int byteCount = inputStream.available();
                if(byteCount > 0)
                {
                    byte[] rawBytes = new byte[byteCount];
                    inputStream.read(rawBytes);
                    final String string=new String(rawBytes,"UTF-8");
                    handler.post(new Runnable() {
                        public void run()
                        {
                            textView.append(string);
                            t[0]=string;
                        }
                    });

                }
            }
            catch (IOException ex)
            {
                stopThread = true;
            }
        }
    }
});

thread.start();
return t[0];

Maybe better solution will be something like this: 也许更好的解决方案将是这样的:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ResultFromThread {

    public static void main(String... args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            return "something";
        });
        String result = cf.get();
    }

}

Instead of ' return "something"; 而不是返回“某物”; ' you just need to add anything you want to do. '您只需要添加您想做的任何事情。

Another solution is (with handling an exception): 另一个解决方案是(处理异常):

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ResultFromThread {

    public static void main(String... args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            return "something";//may also throw an exception
        }).handle((result, throwable) -> {
            if(throwable != null) {
                System.err.println(throwable);//do something with exception
            }
            return result;
        });
        String result = cf.get();
    }
}

In addition to TMH's answer, if you want to manage threads yourself or suggested code seems too complicated for now, here's a simpler way of using CompletableFuture: 除了TMH的答案外,如果您想自己管理线程或建议的代码现在看起来太复杂,这是使用CompletableFuture的一种更简单的方法:

CompletableFuture<Object> completableFuture = new CompletableFuture<>();

new Thread(new Runnable() {
    @Override
    public void run() {
        // computation, reading input streams, etc
        Object result = new Object();

        completableFuture.complete(result);
    }
}).start();

// get() will wait until it's completed
Object resultFromThread = completableFuture.get();

// further processing...

You are setting the value of t[0] inside a new Thread which will run asynchronously. 您正在新线程中设置t[0]的值,该线程将异步运行。 So it is possible that return t[0]; 因此有可能return t[0]; execute before another thread set the value of t[0]. 在另一个线程设置t [0]的值之前执行。 You can use Thread#join write the code as below. 您可以使用Thread#join编写如下代码。

thread.start();
thread.join();
return t[0];

When you call Thread#join the parent thread will wait to finish the Thread on which you have called the join method. 当您调用Thread#join ,父线程将等待完成调用了join方法的Thread However, there are several mechanisms to do that like CountDownLatch and CyclicBarrier or Future but I think Thread#join is the easy and best suited for your use case. 但是,有多种机制可以做到这一点,例如CountDownLatchCyclicBarrierFuture但是我认为Thread#join是最简单且最适合您的用例的机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM