开发者社区> 问答> 正文

从线程中获取返回值的相关问题

程序的方法中有一个 HandlerThread。在线程中改变了一个值,然后我想把它返回到 test()方法。有什么方法能实现呢?
screenshot

展开
收起
蛮大人123 2016-02-15 15:16:37 1865 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    你可以使用一个本地的 final 变量,变量需要是 non-primitive 类型,所以你可以使用一个数组。也需要同步两个线程,例如使用一个 CountDownLatch:

    public void test()
    {   
        final CountDownLatch latch = new CountDownLatch(1);
        final int[] value = new int[1];
        Thread uiThread = new HandlerThread("UIHandler"){
            @Override
            public synchronized void run(){
                value[0] = 2;
                latch.countDown(); // Release await() in the test thread.
            }
        };
        uiThread.start();
        latch.await(); // Wait for countDown() in the UI thread.
        // value[0] holds 2 at this point.
    }

    也可以使用 Executor 和 Callable:

    public void test() throws InterruptedException, ExecutionException
    {   
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() {
                return 2;
            }
        };
        Future<Integer> future = executor.submit(callable);
        // future.get() returns 2
        executor.shutdown();
    }
    2019-07-17 18:43:18
    赞同 展开评论 打赏
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
多IO线程优化版 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载