The Java multithreaded return value USES the example of of callable with futuretask

  • 2020-04-01 03:14:46
  • OfStack

Callable interface is similar to a Runnable, you can see from the name, but a Runnable does not return a result, and can't throw exception, and Callable function more powerful, have carried out with thread, can the return value, the return value is the Future we get it, that is, the return value of the Future can get asynchronous execution task, below to see a simple example


package com.future.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class MyTest {
 //Receive the exception caught in the run method, and then the custom method throws the exception
    //private static Throwable exception;
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String result = "";
  ExecutorService executor = Executors.newSingleThreadExecutor();  
  FutureTask<String> future =  
         new FutureTask<String>(new Callable<String>() {//Using the Callable interface as a construction parameter & NBSP;
           public String call() {  
             //The real task is performed here, and the return value is of type String, which can be of any type
            try {
      Thread.sleep(10000);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      //exception = e;
      //e.printStackTrace();
     }
           return "11111";
         }});  
  executor.execute(future);  
  //Anything else can be done here & NBSP;
  try {  
      result = future.get(5000, TimeUnit.MILLISECONDS); //Gets the result and sets the timeout to 5 seconds. You can also use futures.get () to get the result & NBSP; without setting the execution timeout;
  } catch (InterruptedException e) { 
   //System.out.println(" task canceled ");
   future.cancel(true);  
  } catch (ExecutionException e) {  
   future.cancel(true);  
  } catch (TimeoutException e) {  
   future.cancel(true);  
  } finally {  
      executor.shutdown();  
  }  
  System.out.println("result:"+result);
 }

 

}


Related articles: