如何从线程返回值(java) [英] How to return value from thread (java)

查看:515
本文介绍了如何从线程返回值(java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个类似下面的话题:

I made a thread like this one bellow:

public class MyThread implements Runnable {
  private int temp;

  public MyThread(int temp){
     this.temp=temp;
  }

  @Override
  public void run() {
    temp+=10;
    return;
  }

  public int getTemp() {
    return temp;
  }
}

但是当我尝试通过getTemp使用temp时,我得到0

but when i try to use temp by getTemp i get 0

class Main {
  MyThread foo = new MyThread(10);
  Thread a = new Thread(foo);
  a.start();
  int aa = foo.getTemp();       
  System.out.println(aa);
}

我只想使用我在线程中所做的计算来存储在某些变量中,以备后用.

i just want to use the calculation i did in thread to be stored in some variables for later use.

推荐答案

或直接添加

...
a.start();
a.join(); // Add this
...

等待线程完成后再获取结果.

to wait for the thread to finish before getting the result.

您的问题是,您试图在计算结果之前获取结果.您应该等待线程完成后才能获得结果.这个答案也许不是最好的,但是最简单的.由于其他人已经在使用Executors课程,所以我不想重复他们的答案.但是,在开始使用Executors之前,我会先熟悉Thread及其方法,以帮助您更好地理解线程,因为从您的帖子看来,您可能是该领域的新手.

Your problem is that you're trying to get the result before it has been calculated. You should wait for the thread to finish before getting the result. This answer is perhaps not the best but is the simplest. As other people had already used the Executors class I didnt want to repeat their answers. I would, however, familiarise yourself with Thread and its methods before moving onto Executors to help you get a better understanding of threads as, from your post, it appears you may be a novice in this area.

感谢 l4mpi(在元网站上)指出缺乏解释.

这篇关于如何从线程返回值(java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆