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

从Thread返回值

从Thread返回值

暮色呼如 2019-08-12 16:45:21
从Thread返回值我有一个方法HandlerThread。一个值在内部发生变化Thread,我想将它返回给test()方法。有没有办法做到这一点?public void test(){        Thread uiThread = new HandlerThread("UIHandler"){         public synchronized void run(){             int value;              value = 2; //To be returned to test()         }     };     uiThread.start();}
查看完整描述

3 回答

?
隔江千里

TA贡献1906条经验 获得超10个赞

您可以使用本地最终变量数组。变量必须是非基本类型,因此您可以使用数组。您还需要同步两个线程,例如使用CountDownLatch

public void test(){   
    final CountDownLatch latch = new CountDownLatch(1);
    final int[] value = new int[1];
    Thread uiThread = new HandlerThread("UIHandler"){
        @Override
        public void run(){
            value[0] = 2;
            latch.countDown(); // Release await() in the test thread.
        }
    };
    uiThread.start();
    latch.await(); // Wait for countDown() in the UI thread. Or could uiThread.join();
    // 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 or raises an exception if the thread dies, so safer
    executor.shutdown();}


查看完整回答
反对 回复 2019-08-12
?
子衿沉夜

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

通常你会这样做

 public class Foo implements Runnable {
     private volatile int value;

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

     public int getValue() {
         return value;
     }
 }

然后你可以创建线程并检索值(假设已经设置了值)

Foo foo = new Foo();Thread thread = new Thread(foo);thread.start();thread.join();int value = foo.getValue();

tl;dr线程无法返回值(至少没有回调机制)。您应该像普通类一样引用一个线程并询问该值。


查看完整回答
反对 回复 2019-08-12
?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

您正在寻找的可能是Callable<V>接口代替Runnable,并使用Future<V>对象检索值,这也让您等到计算出值。你可以通过一个ExecutorService你可以得到的来实现这一目标Executors.newSingleThreadExecutor()

public void test() {
    int x;
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Integer> result = es.submit(new Callable<Integer>() {
        public Integer call() throws Exception {
            // the other thread
            return 2;
        }
    });
    try {
        x = result.get();
    } catch (Exception e) {
        // failed
    }
    es.shutdown();}


查看完整回答
反对 回复 2019-08-12
  • 3 回答
  • 0 关注
  • 1132 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信