Callable - understanding of Java's Future Mode

Summary:

  However, in Java, but also it provides the use of Callable and Future operations to achieve access to the results of the task. Callable used to perform tasks, to produce a result, and the results obtained for Future;

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

  Thread ways:
    1. Thread class inherits
    2. implement Runnable
    3. Thread pool
    4.Callable
  regardless of inheritance Thread class or implement Runnable interface, or use the thread pool is no way to solve two problems
    1. thread executes no return value result
    2. thread execution is no way to throw an exception, can only be resolved through their own try-catch

  Callable and Runnable Similarly, at JUC package, the main difference lies in the method call Callable may return value and may throw an exception
  if desired Callable performed, need to support Future implementation class, capable of receiving the return value result, Future implementation class is a FutureTask,

Future Mode

  Future core Moss in that: in addition to a function of the wait time, and such that the time period required to wait for the original may be used to treat other business logic;

  Future Mode: For multi-threaded, if you want to wait for the results thread A thread B, then thread A thread is no need to wait for the B, B know the outcome of the thread, you can get a future Future, and other thread B then take the true result when the result of; 

public  class MyCallable the implements a Callable { 
    @Override 
    public Object Call () throws Exception { 
        System.out.println ( "Call callable interface rewriting method, there may be a return value and an exception is thrown !!!" );
         return "callable" ; 
    } 

    // program a 
    public  static  void main (String [] args) throws ExecutionException, InterruptedException { 
        myCallable myCallable = new new myCallable ();
         // use and acceptance structure FutureTask performed callable 
        FutureTask <String> = stringFutureTask new newA FutureTask, <String> (myCallable);
         // use the thread to perform task task 
        new new the Thread (stringFutureTask) .start ();
         // accept the results, get method blocks will happen 
        System.out.println (stringFutureTask.get ()); 
        System .out.println ( "mycallable finished!" ); 
    } 

}
 
 
public  class MyCallable the implements a Callable { 
    @Override 
    public Object Call () throws Exception { 
        System.out.println ( "Call callable interface rewriting method, there may be a return value and an exception is thrown !!!" );
         return "callable" ; 
    } 

    // Option II: Submit (a Callable Task) 
    public  static  void main (String [] args) throws ExecutionException, InterruptedException { 
        MyCallable myCallable = new new MyCallable ();
         // Create a thread
        ExecutorService = Executors.newFixedThreadPool ExecutorService (3 );
         // create threads mandate and to receive the results of the task 
        Future the Submit = ExecutorService.submit (myCallable);
         // accept the return value, get method blocks the current thread 
        System.out.println (submit. GET ()); 
        System.out.println ( "using the thread pool to perform mycallable, finished !!!" );
         // stop 
        executorService.shutdown (); 
    } 
}

  Common methods:

    V get (): Gets the results of asynchronous execution, if no results are available, this method blocks until the asynchronous computation is completed;

    V get (Long timeout, TimeUnit unit): Asynchronous get the results, if not yo results are available, this method will block, but there is a time limit, if the blocking time exceeds the set timeout time, the method throws an exception;

    boolean isDone (): if the task execution ends, either end or canceled during normal or abnormal, return true;

    boolean isCanceller (): If the task is completed before being canceled, it returns true;

    boolean cancel (boolean mayInterrupRunning): If the job has not started, cancel execution method returns false; if the task has already started, will be interrupted to perform this task cancel method thread a way to try to stop the task execution, if the stop is successful, return true;

    When the task has been started, execute cancel (false) method will have no effect (normal thread to execute to completion) for tasks executing thread, then return false;

    When the task has been started, execute cancel method returns false, MayInterruptRunning parameter indicates whether to interrupt the execution of threads;

    Indeed Future provides three functions:

      1. To interrupt task execution;

      2. Determine if the task execution is completed;

      3. Get the results of the task execution is completed;

  Obstructive get () method

public class FutureGet {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor=Executors.newFixedThreadPool(2);
        //创建一个Callable,三秒返回String类型
        Callable callable = new Callable() {
            @Override
            public Object call() throws Exception {
                Thread.sleep(3000);
                System.out.println("callable方法执行!");
                return "callable";
            } 
        }; 
        System.out.println ( "before submitting tasks:" + getStringDate ()); 
        Future Future = executor.submit (Callable); 
        System.out.println ( "after providing the task before obtaining results:" + getStringDate ( )); 
        System.out.println ( "Get return value:" + Future.get ()); 
        System.out.println ( "acquired after the result:" + getStringDate ()); 
    } 

    public  static String getStringDate () { 
        DATE DATE = new new DATE (); 
        the SimpleDateFormat the format = new new the SimpleDateFormat ( "HH: mm: SS" );
        String dataString = format.format(date);
        return dataString;
    }
}

    You can see from the above output, after mobilizing submit to submit the task, could have been the main thread continues to run to future.get () when it is blocked, wait until the task is completed, get the value returned, the main thread will continue to run;

  Obstructive because calls get () method, the task is not finished, it will wait until the task is completed, forming a blockage;

  Task when you call the submit method begins execution, if when you call the get method, the task has been executed, then it will not cause obstruction;

  Before calling the following methods to sleep four seconds, this time can immediately return value:

  submit(Runnable task)

    Because Runnable is no return value, so if you submit a Runnable words, get definitely get the value for the null;

public class SubmitRunnable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor= Executors.newFixedThreadPool(2);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Future future = executor.submit(runnable);
        System.out.println("获得返回值:"+future.get());
    }
}

submit(Runnable task,T result)

  Although not Runnable passed directly back to the content, but can pass through a support submit (Runnable task, T result), this carrier acquires the return value;

public class Data {
    String name;
    String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

  Runnable passed in the constructor of:

public class MyThreadData implements Runnable {
    Data data;

    public MyThreadData(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
            System.out.println("线程执行:");
            data.setName("张三");
            data.setSex("女");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] arg) throws ExecutionException, InterruptedException {
        ExecutorService executor= Executors.newFixedThreadPool(2);
        Data data = new Data();
        Future<Data> submit = executor.submit(new MyThreadData(data), data);
        System.out.println("返回结果:"+submit.get().getName()+",sex:"+submit.get().getSex());
    }
}

  get(long var1,TimeUnit var3)

public class GetTime {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ExecutorService executor= Executors.newFixedThreadPool(2);
        //创建一个Callable,三秒返回String类型
        Callable callable = new Callable() {
            @Override
            public Object call() throws Exception {
                Thread.sleep(3000);
                System.out.println("callable方法执行!");
                return "callable"; 
            } 
        }; 
        (System.out.println "before submitting tasks:" + getStringDate ()); 
        Future Future = executor.submit (Callable); 
        System.out.println ( "after providing the task before obtaining results:" + getStringDate ()); 
        System.out.println ( "Get return value:" + Future.get (2 , TimeUnit.SECONDS)); 
        System.out.println ( "acquired after the result:" + getStringDate ()); 
    } 

    public  static String getStringDate () { 
        a Date DATE = new new a Date (); 
        the SimpleDateFormat the format = new new the SimpleDateFormat ( "HH: mm: SS");
        String dataString = format.format(date);
        return dataString;
    }
}

Guess you like

Origin www.linuxidc.com/Linux/2020-03/162766.htm
Recommended