Java multithreaded Programming: Callable, Future and Futuretask (multithreaded Programming IV)

Source: Internet
Author: User
Tags java se

Java Multithreading-Concepts & Create Startup & interrupts & Daemon Thread & priority & Thread State (one of multithreaded programming)
Java multithreading synchronization and communication between threads & Consumer producer Mode & Deadlock &thread.join () (Multithreaded Programming II)
A brief analysis of the threadpoolexcutor&scheduledthreadpoolexecutor of Java&android thread pool-executor Framework (Multithread Programming III)
Java Multithreading: Callable, Future and Futuretask (multithreaded programming of the four)

Through the previous several studies, we know that there are two ways to create a thread, one is to implement the Runnable interface, and the other is to inherit thread, but both of these methods have the disadvantage of not getting the return result after the execution of the task is done, so what if we want to get the return result? Also remember the callable interface and future interface mentioned in the executor frame structure. , yes, with the introduction of callable and future from Java SE 5.0, the threads they build, the execution results can be obtained after the task is executed, and today we'll talk about the third way to create threads is to implement the callable interface.


1.callable<v> Interface Let's review the Java.lang.Runnable interface first and declare run (), whose return value is void, and of course we can't get the result.

Public interface Runnable {public
    abstract void Run ();
}
And the callable interface is defined as follows
Public interface Callable<v> { 
      V call   ()   throws Exception; 
The interface declares a method named Call (), and the method can have a return value of V, or it can throw an exception. Well, we know so much about the interface, and here's how to use it, as we said in the previous article, whether it's the implementation class of the Runnable interface or the implementation class of the callable interface, Can be executed by threadpoolexecutor or Scheduledthreadpoolexecutor, threadpoolexecutor or Scheduledthreadpoolexecutor are implemented. Excutorservice interface, and therefore callable need to be used in conjunction with the Excutorservice in the executor framework, let's look at the methods that Executorservice provides:
<T> future<t> Submit (callable<t> Task);
<T> future<t> Submit (Runnable task, T result);
Future<?> Submit (Runnable Task);
The first method: Submit commits a task that implements the callable interface, and returns the future that encapsulates the results of the asynchronous computation. The second method: Submit commits a task that implements the Runnable interface, and specifies the result object that is returned when the future Get method is invoked. The third method: Submit commits a task that implements the Runnable interface, and returns the future that encapsulates the results of the asynchronous computation. So we just create our thread object (implement callable interface or Runnable interface), and then commit it to the thread pool through the above 3 methods. Also note that, in addition to our own implementation of callable objects, we can also use the factory class executors to wrap a runnable object into a callable object. The Executors factory class provides the following methods:
public static callable<object> callable (Runnable Task) public
static <T> callable<t> callable ( Runnable task, T result)
2.future<v> interface
The Future<v> interface is used to obtain the results of an asynchronous computation, which is simply to obtain (get ()) the results of a specific runnable or callable object's task execution, cancel (cancel), and determine whether or not to complete the operation. Let's look at the source code for the Future interface:
Public interface Future<v> {
    boolean mayinterruptifrunning);
    Boolean iscancelled ();
    Boolean isdone ();
    V get () throws Interruptedexception, Executionexception;
    V get (long timeout, timeunit) throws Interruptedexception, Executionexception, timeoutexception;
}
Method Resolution: V get (): Gets the result of an asynchronous execution, and if no results are available, this method blocks until the asynchronous computation completes. V Get (Long timeout, timeunit unit): Gets the results of the asynchronous execution, and if no results are available, this method blocks, but there is a time limit, and if the blocking time exceeds the set timeout time, the method throws an exception. Boolean Isdone (): Returns True if the execution of a task ends, whether it is a normal end or a cancellation or an exception occurs. Boolean Iscanceller (): Returns True if the task is canceled before it completes. Boolean Cancel (Boolean mayinterruptrunning): If the task has not started, execute cancel (...) method returns False, and if the task is already started, the execution of the Cancel (true) method attempts to stop the task by interrupting the execution of the task thread, and returns True if the stop succeeds, and the execution of cancel (false) when the task is started Method will not have an effect on the task thread being executed (let the thread execute to completion), return false at this time, and execute Cancel (...) when the task is completed. Method will return false. The mayinterruptrunning parameter indicates whether the thread in execution is interrupted. By means of analysis we also know that in fact future provides 3 functions: (1) The ability to interrupt the execution of the task (2) to determine whether the task is completed (3) to obtain the completion of the task execution results. But we have to understand that future is just an interface, we can't create objects directly, so we need the implementation class Futuretask. 3.FutureTask class
Let's take a look at Futuretask's implementation.
public class Futuretask<v> implements runnablefuture<v> {
Futuretask class implements the Runnablefuture interface, let's look at the implementation of the Runnablefuture interface:
Public interface runnablefuture<v> extends Runnable, future<v> {
    void Run ();
}
Analysis: Futuretask In addition to the implementation of the future interface is also implemented Runnable interface, so futuretask can also be directly submitted to the executor implementation. Of course, you can also invoke thread execution directly (Futuretask.run ()). Next, we analyze the 3 states in which the Futuretask.run () is being executed: (1) is not started, the Futuretask.run () method has not been executed before, Futuretask is not in the startup state, when a futuretask is created, This futuretask is also in an futuretask.run state before the method is executed. (2) is started, Futuretask.run () is executed, Futuretask is in the started state. (3) completed, the Futuretask.run () method completes the normal end, or is canceled or throws an exception and ends, the futuretask is in complete state.
Let's take a look at the Futuretask Method execution diagram (method and future interface is basically the same, here is not too much description)

Analysis: (1) When the Futuretask is in an open or started state, if we execute the Futuretask.get () method at this time, it will cause the calling thread to block, and when Futuretask is in the completed state, execute Futuretask.get () method causes the calling thread to immediately return the result or throw an exception. (2) When Futuretask is in an open state, executing the Futuretask.cancel () method will cause the task to never be executed. When Futuretask is in a started state, the Execute cancel (true) method attempts to stop the task by interrupting the execution of this task thread, and if the task cancels successfully, cancel (...) Returns true, but if the Cancel (false) method does not affect the executing task thread (let the thread execute to completion), Cancel (...) returns FALSE. When the task is completed, execute cancel (...) Method will return false. Finally, we give two kinds of constructors of Futuretask:
Public Futuretask (callable<v> callable) {
} public
Futuretask (Runnable Runnable, V result) {
}
The use of 3.callable<v>/future<v>/futuretask
Through the above introduction, we have a clearer understanding of the callable,future,futuretask, then what is the use of them in the end. We said earlier that by creating threads in this way, the biggest benefit is to be able to return the results, add to the scene, we now need to calculate a data, and the calculation of the data is time-consuming, and we have to use the following procedures to the data results, then this time callable is not the best choice. We can open a thread to perform the calculation, while the main thread continues to do other things, and then we need to use the future to get the data. Let's write an example of this 3.1 using Callable+future to get execution results
The callable implementation class is as follows:
Package com.zejian.Executor;
Import java.util.concurrent.Callable;
/**
 * @author Zejian
 * @time March 15, 2016 afternoon 2:02:42
 * @decrition Callable Interface instance/public
class Callabledemo implements callable<integer> {
	
	private int sum;
	The @Override public
	Integer called () throws Exception {
		System.out.println ("callable child thread) begins to compute. ");
		Thread.Sleep ();
		
		for (int i=0; i<5000;i++) {
			sum=sum+i;
		}
		System.out.println ("Callable child thread calculation ends.") ");
		return sum;
	}
Callable execution test classes are as follows:

Package com.zejian.Executor;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
/**
 * @author Zejian
 * @time March 15, 2016 afternoon 2:05:43
 * @decrition callable Execute TEST class
 * * * Public
class callabletest {public
	
	static void Main (string[] args) {
		//create thread pool
		executorservice es = Executors.newsinglethreadexecutor ();
		Create the Callable Object task
		Callabledemo caltask=new Callabledemo ();
		Submit tasks and obtain execution results
		future<integer> Future =es.submit (caltask);
		Close the thread pool
		es.shutdown ();
		try {
			thread.sleep ();
		System.out.println ("main thread in performing other tasks");
		
		if (Future.get ()!=null) {
			//output obtained results
			System.out.println ("Future.get ()-->" +future.get ());
		} else{
			//output obtained results
			System.out.println ("Future.get () not get Results");
		}
		
		catch (Exception e) {
			E.printstacktrace ();
		}
		System.out.println ("Main thread in Execution complete");
	}

Execution results:

Callable the child thread begins to compute.
The main thread callable the child thread calculation at the end of other tasks. Future.get ()-->12497500 The main thread is completed in execution
3.2 Using Callable+futuretask to get execution results
Package com.zejian.Executor;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
Import Java.util.concurrent.FutureTask; /** * @author Zejian * @time March 15, 2016 afternoon 2:05:43 * @decrition callable Execute TEST class * * public class Callabletest {public static void Main (string[] args) {////Create thread pool//Executorservice es = Executors.newsinglethreadexecutor ();///Create Callab
Le object Task//Callabledemo caltask=new Callabledemo ();
Submit tasks and obtain execution results//future<integer> Future =es.submit (caltask);
		
		Close the thread pool//Es.shutdown ();
		Create thread pool Executorservice es = Executors.newsinglethreadexecutor ();
		Create the Callable Object task Callabledemo caltask=new Callabledemo ();
		Create Futuretask futuretask<integer> futuretask=new futuretask<> (caltask);
		Es.submit (Futuretask) for the implementation of the Mission;
		Close the thread pool Es.shutdown ();
		try {thread.sleep (2000);
		
		System.out.println ("main thread in performing other tasks"); if (Futuretask.get ()!=null) {//output gets the result System.out. println ("Futuretask.get ()-->" +futuretask.get ());
		}else{//Output obtained results System.out.println ("Futuretask.get () did not get the result");
		} catch (Exception e) {e.printstacktrace ();
	} System.out.println ("Main thread in Execution complete"); }
}
Execution results:
Callable the child thread begins to compute. The main thread callable the child thread calculation at the end of other tasks. Futuretask.get ()-->12497500 The main thread is completed in execution

Main reference: Java concurrent Programming Art related article: http://www.cnblogs.com/dolphin0520/p/3949310.html

Related Article

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.