How to return value from thread (java)

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

    In this case, you have to use Callable instead of Runnable (very similar): http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html

    public class MyThread implements Callable { 
    
        private int temp;
    
        public MyThread(int temp){
             this.temp=temp;
        }
        @Override
        public Integer call() {
            temp+=10;
            return temp;
        }
    
    }
    
    
    public static void main(String[] args) throws InterruptedException, ExecutionException {
               ExecutorService service =  Executors.newSingleThreadExecutor();
               MyThread myTask = new MyThread(10);
               Future future = service.submit(myTask);
               Integer result = future.get();
               System.out.println(result);
    }
    

提交回复
热议问题