How to return value from thread (java)

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

    You can try these code. By using Future you can hold the value return when the thread end:

    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    /**
     * @author mike
     * @date Sep 19, 2014
     * @description
     */
    public class Calc {
        private static class MyCallable implements Callable {
            private int temp = 0;
    
            public MyCallable(int temp) {
                this.temp = temp;
            }
    
            @Override
            public Integer call() {
                temp += 10;
                return temp;
            }
        }
    
        public static void main(String[] args) {
            MyCallable foo = new MyCallable(10);
            try {
                Future result = Executors.newCachedThreadPool().submit(foo);
                System.out.println(result.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题