csh_34 2013-03-04 05:11 采纳率: 0%
浏览 2129
已采纳

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

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

public void test()
{   
    Thread uiThread = new HandlerThread("UIHandler"){
        public synchronized void run(){
            int value; 
            value = 2; //To be returned to test()
        }
    };
    uiThread.start();
}
  • 写回答

2条回答

  • Baby_Bonnie 2013-03-04 06:23
    关注

    你可以使用一个本地的 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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘