How to return value from thread (java)

前端 未结 5 1429
盖世英雄少女心
盖世英雄少女心 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:46

    There are a few ways to "share" variables with Threads.

    The problem with your code is that you are passing an int which is passed by value. This means that temp and this.temp is not the same variable.

    Using a Future as other answers suggest is one way that you can share variables. Using a Future, you can ensure that the Thread has finished before actually fetching the result of that Threads execution so might be more relevant to you.

    Other ways of sharing variables among Threads that are Thread-safe, but does not guarantee that the Thread has finished execution:

    • pass an AtomicInteger and use the set method to set value.
    • use a synchronized getter method that returns the Threads value.

提交回复
热议问题