为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

饮歌长啸 2019-03-13 12:15:04
程序的方法中有一个 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 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

你可以使用一个本地的 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-04-27
?
米脂

TA贡献1836条经验 获得超3个赞

通常应该这样

public class Foo extends Runnable {
     private volatile int value;

     @Override
     public void run() {
        value = 2;
     }

     public int getValue() {
         return value;
     }
 }

然后你可以创建线程,检索值(鉴于已设置的值)

Thread t = new Thread(new Foo());
t.start();
// ... 
int value = t.getValue();


查看完整回答
反对 回复 2019-04-27
  • 2 回答
  • 0 关注
  • 593 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号