从线程返回值

新手上路,请多包涵

我有一个带有 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();
}

原文由 Neeta 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 344
2 个回答

通常你会这样做

 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 线程不能返回值(至少不能没有回调机制)。应该像普通类一样引用线程,求值。

原文由 Johan Sjöberg 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用本地最终变量数组。该变量需要是非原始类型,因此您可以使用数组。您还需要同步这两个线程,例如使用 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.
}

您还可以像这样使用 ExecutorCallable

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

原文由 Adam Zalcman 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题