Java threads learning 07 - Callable and Future

 And contracting of learning, this help is Callable and Future , Talia very interesting, to produce a result, to get a result. 


               Callable interface is similar to Runnable , it can be seen from the name, but the Runnable not return a result, and returns the result can not throw exceptions, but Callable function more powerful, after execution thread, return values, the return value can be is to get the Future, that is to say, Future can get the return value of the asynchronous task execution, let's look at a simple example:
 

public class CallableAndFuture {
    public static void main(String[] args) {
        Callable<Integer> callable = new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        };
        FutureTask<Integer> future = new FutureTask<Integer>(callable);
        new Thread(future).start();
        try {
            Thread.sleep(5000);// 可能做一些事情
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

              FutureTask implements two interfaces, Runnable and Future, so both threads can be executed as Runnable, but also as Future Callable get the return value, then the use of this combination of what good is it? Suppose there is a very time-consuming return value to be calculated, and the return value is not immediately need, then you can use this combination to calculate the return value with another thread, the current thread before using this return value can do other operation, wait until you need the return value, and then get through the Future, not Miya! Here is a description of Future pattern: http: //openhome.cc/Gossip/DesignPattern/FuturePattern.htm. 
 

Let's look at another way to use Callable and Future, submit method performed by the ExecutorService Callable and returns Future, code is as follows:

public class CallableAndFuture {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<Integer> future = threadPool.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        });
        try {
            Thread.sleep(5000);// 可能做一些事情
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

 Code is not simplified a lot, ExecutorService inherited from the Executor, its purpose is for us to manage the Thread object, which simplifies concurrent programming, Executor the life cycle to manage threads we do not show is the preferred way to start the task after 5 JDK. 
       Executing a plurality of tasks with a return value, and obtaining a plurality of return value, as follows:
 

public class CallableAndFuture {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
        for(int i = 1; i < 5; i++) {
            final int taskID = i;
            cs.submit(new Callable<Integer>() {
                public Integer call() throws Exception {
                    return taskID;
                }
            });
        }
        // 可能做一些事情
        for(int i = 1; i < 5; i++) {
            try {
                System.out.println(cs.take().get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
} 

In fact, you can not use CompletionService, you can create a collection Future type of equipment, with the task of submitting Executor return value to the collection, and finally out through the collection of data, the code slightly. Updated on 2016-02-05, comments on this statement triggered a discussion, in fact, I did not make it clear, I'm sorry. Here again elaborate: submit to CompletionService The Future is in order to complete the arrangement, a practice in Future is arranged in the order added . So the difference between these two methods is like a review as described in fishjam.
 

 

 

Guess you like

Origin blog.csdn.net/yuhaibao324/article/details/93149639