从java线程返回值

从java线程返回值,java,multithreading,inputstream,Java,Multithreading,Inputstream,我正试图从Arduino接收串行数据,我想将该值存储在一个变量中,我该怎么做? 我尝试了下面的代码,但它没有在数组元素t[0]中存储string的值 或者有没有一种方法来存储从输入流读取的数据 final String[] t = new String[1]; t[0]="0"; final Handler handler = new Handler(); stopThread = false; buffer = new byte[1024]; Thread thread = new Thr

我正试图从Arduino接收串行数据,我想将该值存储在一个变量中,我该怎么做? 我尝试了下面的代码,但它没有在数组元素t[0]中存储string的值

或者有没有一种方法来存储从输入流读取的数据

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];

您正在异步运行的新线程内设置
t[0]
的值。所以有可能
返回t[0]在另一个线程设置t[0]的值之前执行。您可以使用
Thread#join
编写如下代码

thread.start();
thread.join();
return t[0];
调用
Thread#join
时,父线程将等待完成调用
join
方法的
Thread

然而,有几种机制可以做到这一点,比如
CountDownLatch
CyclicBarrier
Future
,但我认为线程#连接是最简单、最适合您的用例的。也许更好的解决方案是这样的:

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

}
import java.util.concurrent.CompletableFuture;
导入java.util.concurrent.ExecutionException;
公共类ResultFromThread{
公共静态void main(字符串…参数)抛出ExecutionException、InterruptedException{
CompletableFuture cf=CompletableFuture.SupplySync(()->{
返回“某物”;
});
字符串结果=cf.get();
}
}
而不是“返回“某物”“您只需要添加任何您想做的事情

另一种解决方案是(处理异常):

import java.util.concurrent.CompletableFuture;
导入java.util.concurrent.ExecutionException;
公共类ResultFromThread{
公共静态void main(字符串…参数)抛出ExecutionException、InterruptedException{
CompletableFuture cf=CompletableFuture.SupplySync(()->{
返回“something”;//还可能引发异常
}).handle((结果,可丢弃)->{
if(可丢弃!=null){
System.err.println(throwable);//执行异常操作
}
返回结果;
});
字符串结果=cf.get();
}
}

除了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...
CompletableFuture CompletableFuture=newcompletablefuture();
新线程(newrunnable()){
@凌驾
公开募捐{
//计算、读取输入流等
对象结果=新对象();
可完成的未来。完成(结果);
}
}).start();
//get()将等待它完成
对象resultFromThread=completableFuture.get();
//进一步处理。。。

但是,如果原始海报只使用一个线程来执行此操作,那么使用线程就没有意义了。检查可能会有所帮助,它使用callable从执行的线程返回值。有关可调用检查的详细信息。
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...