How to return value from thread (java)

前端 未结 5 1471
盖世英雄少女心
盖世英雄少女心 2021-01-15 11:19

I made a thread like this one bellow:

public class MyThread implements Runnable {
  private int temp;

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


        
5条回答
  •  情歌与酒
    2021-01-15 11:44

    Or simply add

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

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

    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.

    Thanks to l4mpi (on the meta site) for pointing out the lack of explanation.

提交回复
热议问题