How to return value from thread (java)

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

    Use Callable instead of a Runnable, it will return a Future that you can use to retrieve the value once it is done.

    You can use a named class instead of a lambda expression if you want to.

    import java.util.concurrent.*;
    
    public class ReturnValueFromThread {
        public static void main(String[] args) throws Exception {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            Future foo = executor.submit(() -> {
                return doWork();
            });
    
            System.out.println("We will reach this line before doWork is done.");
            System.out.println(foo.get()); // Will wait until the value is complete
            executor.shutdown();
        }
    
        private static double doWork() throws Exception {
            Thread.sleep(2000);
            return Math.random();
        }
    }
    
        

    提交回复
    热议问题