Java multi-thread series-Callable and ure of "JUC thread pool" 06

Source: Internet
Author: User

Callable and Future introduction Callable and Future are interesting combinations. When we need to obtain the thread execution results, we need to use them. Callable is used to generate results, and Future is used to obtain results. 1. Callable is an interface that contains only one call () method. Callable is a task that returns results and may throw exceptions. For ease of understanding, we can compare Callable to a Runnable interface, while Callable's call () method is similar to Runnable's run () method. Callable source code: public interface Callable <V> {V call () throws Exception;} Description: Callable supports generics. 2. Future is an interface. It is used to represent the result of asynchronous calculation. It provides a method to check whether the calculation is complete, waiting for the calculation to be completed and obtaining the calculation result. The source code of Future is as follows: copy the code public interface Future <V >{// try to cancel the execution of this task. Boolean cancel (boolean mayInterruptIfRunning) // returns true if the job is canceled before it completes. Boolean isCancelled () // returns true if the task has been completed. Boolean isDone () // wait until the calculation is complete and obtain the result if necessary. V get () throws InterruptedException, ExecutionException; // if necessary, wait for the result to be obtained after the time specified for the calculation to complete (if the result is available ). V get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;} copy the Code Description: Future is used to represent the asynchronous calculation result. Its implementation class is FutureTask. Before explaining FutureTask, let's take a look at the relationship between Callable, Future, and FutureTask as follows: (01) RunnableFuture is an interface, it inherits the Runnable and Future interfaces. The source code of RunnableFuture is as follows: public interface RunnableFuture <V> extends Runnable and Future <V> {void run () ;}( 02) FutureTask implements the RunnableFuture interface. Therefore, we also say that it implements the Future interface. For example and source code analysis (based on JDK1.7.0 _ 40), we first use an example to see the basic usage of Callable and ure, and then analyze the implementation principles of the example. Copy code 1 import java. util. concurrent. callable; 2 import java. util. concurrent. future; 3 import java. util. concurrent. executors; 4 import java. util. concurrent. executorService; 5 import java. util. concurrent. executionException; 6 7 class MyCallable implements Callable {8 9 @ Override 10 public Integer call () throws Exception {11 int sum = 0; 12 // execute task 13 for (int I = 0; I <100; I ++) 14 sum + = I; 15 // return su M; 16 return Integer. valueOf (sum); 17} 18} 19 20 public class CallableTest1 {21 22 public static void main (String [] args) 23 throws ExecutionException, interruptedException {24 // create a thread pool 25 ExecutorService pool = Executors. newSingleThreadExecutor (); 26 // create a task with a returned value 27 Callable c1 = new MyCallable (); 28 // execute the task and obtain the Future object 29 Future f1 = pool. submit (c1); 30 // output result 31 System. out. println (f1.get (); 32 // close the thread pool 33 pool. shutdown (); 34} 35} copy the code running result: 4950 result Description: In the main thread, create a thread pool through newSingleThreadExecutor. Create the Callable object c1, submit c1 to the thread pool for processing through pool. submit (c1), and save the returned results to the Future object f1. Then, we get the result saved in Callable through f1.get (), and close the thread pool through pool. shutdown. 1. submit () in java/util/concurrent/AbstractExecutorService. java implementation, its source code is as follows: copy the code public <T> Future <T> submit (Callable <T> task) {if (task = null) throw new NullPointerException (); // create a RunnableFuture object RunnableFuture <T> ftask = newTaskFor (task); // execute "task ftask" execute (ftask ); // return "ftask" return ftask;} copy the Code Description: submit () creates the RunnableFuture object ftask through newTaskFor (task. Its source code is as follows: protected <T> RunnableFuture <T> newTaskFor (Callable <T> callable) {return new FutureTask <T> (callable);} 2. futureTask constructor: copy the code public FutureTask (Callable <V> callable) {if (callable = null) throw new NullPointerException (); // callable is a Callable object this. callable = callable; // state records the status of FutureTask this. state = NEW; // ensure visibility of callable} copy code 3. run () Method, we continue to return to the source code of submit. After newTaskFor () creates an ftask object, the task is executed through execute (ftask. At this time, ftask is executed as a Runnable object, and the run () method of ftask is called. The run () method of ftask is in java/util/concurrent/FutureTask. java implementation, the source code is as follows: copy the code public void run () {if (state! = NEW |! UNSAFE. compareAndSwapObject (this, runnerOffset, null, Thread. currentThread () return; try {// assign the callable object to c. Callable <V> c = callable; if (c! = Null & state = NEW) {V result; boolean ran; try {// execute the Callable call () method and save the result to the result. Result = c. call (); ran = true;} catch (Throwable ex) {result = null; ran = false; setException (ex) ;}// if the operation is successful, save the result if (ran) set (result) ;}} finally {runner = null; // set "state mark" int s = state; if (s> = INTERRUPTING) handlePossibleCancellationInterrupt (s);} copy the Code Description: The call () method of the Callable object is executed in run, and finally save the result to the result, and save the result through set (result. Call the get () method of FutureTask and return the value saved through set (result.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.