从线程java返回值

时间:2018-04-23 08:03:25

标签: java multithreading inputstream

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

中存储字符串的值

或者有没有办法存储输入流的读数?

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

3 个答案:

答案 0 :(得分:1)

也许更好的解决方案是这样的:

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

}

取代&#39; 返回&#34;某事&#34;; &#39;你只需要添加你想做的任何事情。

另一个解决方案是(处理例外):

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

答案 1 :(得分:1)

除了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...

答案 2 :(得分:0)

您正在异步运行的新线程中设置t[0]的值。因此,return t[0];可能在另一个线程设置t [0]的值之前执行。您可以使用Thread#join编写如下代码。

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

当您致电Thread#join时,父线程将等待您完成调用Thread方法的join。 但是,有几种机制可以像CountDownLatchCyclicBarrierFuture那样做,但我认为Thread#join是最简单的,最适合您的用例。