java - 如何使用另一个线程从方法中获取结果

标签 java android multithreading

我在 Otherclass 类中有方法 test(),它返回 String 结果:

public class Otherclass {
    int i = 0;

    public String test()
    {       
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                 System.out.println("GoToThread");
                 while(i < 10) {
                    i++;
                    System.out.println("value "+i);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }                   
                }
            }               
        });
        t.start();

        String result = "result value i = "+i;

        return result;
    }
}

我从主类调用这个方法

Otherclass oc = new Otherclass();
System.out.println(oc.test());

并希望得到 result value i = 10 的结果 但是 Otherclass 中的线程在方法结果返回后运行,我得到的结果为:

result value i = 0
GoToThread
value1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 10

求助,运行Thread后如何获取test()方法的结果?

最佳答案

修复代码

您需要使用 join() 等待您的 t 线程完成:

t.start();
t.join(); // this makes the main thread wait for t to finish
String result = "result value i = "+i;

另一种选择

考虑实现 Callable如果您需要从线程返回一个值。例如:

public static void main(String[] args) throws Exception {

  Callable<Integer> worker = new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
      Integer i = 0;

      while (i < 10) {
        i++;
        System.out.println("value " + i);
        Thread.sleep(500);
      }

      return i;
    }
  };

  Future<Integer> result = Executors.newSingleThreadExecutor().submit(worker);
  System.out.println(result.get());
}

输出是:

value 1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 10
10

关于java - 如何使用另一个线程从方法中获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22716685/

相关文章:

Android ToolBar菜单项选中状态颜色(Over flow menu items selected color)

iphone - 当目标对象已经为 NULL 时,iOS 如何捕获发送到实例的无法识别的选择器异常?

php - 为什么 PHP 开发人员无法根据线程范围提供 setlocale 函数

java - 我们可以将线程加入方法放在同步方法中吗

java - 如何在java二叉树中实现通用的中序遍历?

java - 检测无效的 XML 字符

java - 外部ID概念?

java - Java 中的并发性——如何测试它?

android - 带有 HTML 选择标签颜色的 iOS9 Cordova 元素

androidcamera2预览表面在使用后台服务的情况下