Multithreading callable and future

Source: Internet
Author: User
Tags thread class

----------------------Android Training, Java training, and look forward to communicating with you. ----------------------

About multithreading callable and future
Implementing multithreading we can inherit the thread class or implement the Runnable interface, wrapping the run () method into a thread executor through the thread class, but neither of these methods directly wraps any method directly into the thread execution body, such as a method with a return value, or a method of throwing an exception.
Starting with Java 5, Java provides the callable interface, an enhanced version of the Runnable interface, which provides a call () method that can act as a thread executor, but the call () method is more powerful than the run () method.
The call () method can have a return value.
The call () method can declare an exception to be thrown.
So we can simply provide a callable object as target for thread, and the thread execution body is the call () method of the Callable object.

The lookup API found that the callable interface is a new interface to Java 5, and that he is not a sub-interface of the runnable interface, so the callable object cannot be used directly as target for the thread class. The callable method also has a return value--call () method, which cannot be invoked directly, but is invoked as a thread execution body.

In the tool development package, Java 5 provides a future interface to represent the return value of the call () method in the callable interface, and provides a Futuretask implementation class for the future interface, which implements the future interface, and implements the Runnable interface--can be used as target for the thread class. In fact, the Futuretask class here implements a bridge that connects callable objects and thread objects. It should be noted that the callable interface has generic restrictions, and the generic parameter type in the callable interface is the same as the return value type of the call () method.

Interface callable<v>
V call () throws Exception evaluates the result and throws an exception if the result cannot be computed.
Class Futuretask<v> V-the result type returned by this futuretask get method.
The public V get () throws interruptedexception,executionexception, if necessary, waits for the calculation to complete and then gets its result.


Creating and starting a thread step with a return value is similar to implementing the Runnable interface:
1. Create the implementation class for the callable interface and implement the call () method
2. Create an instance of the callable implementation class and use the Futuretask class to wrap the callable object
3. Create and start a new thread using the Futruetask object as target of the thread object.
4. Call the Get () method of the Futruetask object to obtain the return value after the completion of the child thread execution.
Cases:

Import java.util.concurrent.Callable;
Import Java.util.concurrent.FutureTask;

public class Thirdthread implements callable<integer>{public
	Integer call () {
		int i = 0;
		for (; i<60; i + +) {
			System.out.println (Thread.CurrentThread (). GetName () + "loop variable i is the value:" + i);
		}
		return i;
	}
	
	public static void Main (string[] args) {
		
		Thirdthread RT = new Thirdthread ();//Create callable Object
		futuretask< integer> task = new futuretask<integer> (RT);//use Futruetask to wrap callable object for
		(int i=0; i<60; i++) {
			System.out.println (Thread.CurrentThread (). GetName () + "-------" + i);
			if (i = =) {
				new Thread (task, "Thread with return value"). Start ();//actually create and start the thread with the callable object
			}
		try{
			System.out.println ("The return value of the child thread:" + task.get ());
		}
		catch (Exception e) {
			e.printstacktrace ();}}}


Summarize:
Multiple threads can be implemented by inheriting the thread class or implementing runnable, callable interfaces, although implementing the Runnable interface is essentially the same as implementing the callable interface, except that the method defined in the callable interface has a return value and can be declared to throw an exception. Multiple threads are created in a way that implements Runnable, callable interfaces, and the thread class only implements the Runnable interface or callable interface, and can also inherit other classes in which multiple threads can share the same target object. So it is very suitable for multiple identical threads to handle the same resource situation, so that the CPU, code and data can be separated to form a clear model, and better embody the object-oriented thinking.

Personal understanding: The thread class can be understood as a generation factory, while the Runnable interface is the raw material, the factory is responsible for processing the standard raw materials into finished products, while the callable interface is another material, He needs to be futruetask processed into semi-finished products (i.e. materials that meet the runnable standard) and then processed at the thread factory.

----------------------Android Training, Java training, and look forward to communicating with you. ----------------------details please check: Http://edu.csdn.net/heima

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.