Implementation of Java Multi-thread callable and future interface

Source: Internet
Author: User
Tags exception handling

Callable and future


The callable interface defines a call method that can act as the executing body of a thread, but the call method is more powerful than the Run method:


A, call method can have return value
B, the call method can declare an exception thrown

The callable interface is a new interface after JDK5 and is not a runnable sub-interface, so the callable object cannot be used directly as target for thread. And the call method also has a return value,
The call method cannot be called directly, it is invoked as the thread's execution body. Then how to receive the return value of the call method.
JDK1.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 the target of thread.

The future interface defines the following common methods for controlling his associated callable tasks:

A, Boolean Cancel (Boolean mayinterruptlfrunning): Attempting to cancel the associated callable task in the future
B, V get (): Returns the return value of the call method in the callable task, calling this method will cause the thread to block and must wait until the child thread finishes before getting the return value
C, V get (long timeout, timeunit unit): Returns the return value of the call method in the callable task, which blocks the maximum time specified by the timeout and the unit.
If the callable task still does not return a value after a specified time, the timeoutexception will be thrown.
D, Boolean iscancelled: Returns True if the callable task is canceled before it is properly completed.
E, Boolean Isdone: Returns True if the callable task is completed

The steps to create, and start a thread with a return value are as follows:

First, create the implementation class for the callable interface and implement the Call method, the return value of the call method, and act as the thread's execution body.
Second, create an instance of the callable implementation class and use the Futuretask class to wrap the callable object, which encapsulates the return value of the call method for that callable object
Third, create and start a new thread using the Futuretask object as target of the thread object
The method of calling the Futuretask object to get the return value after the child thread execution ends


1. The executor framework uses runnable as the basic expression of its mission. Runnable is rather limited, cannot return a value, and cannot throw a checked exception, which is more difficult to handle for complex and time-consuming computations
2. This has resulted in the callable and future tasks and the overall management of the tasks

3,

1) callable waits for the return value at the main entry point and prepares the-call for possible exceptions.

2) executors contains tools to encapsulate other types of tasks into a callable, such as runnable and java.security.PrivilegedAction. Runnable and callable describe abstract computational tasks.

3 These tasks are limited, have a clear start and end, but are cumbersome for very time-consuming tasks, and can be canceled for tasks that have been committed but not yet started, but for tasks that have already started, they can only be canceled if they respond to interruptions.

4,

1) Future describes the lifecycle of the task and provides relevant methods to obtain the results of the task, cancel the task, and verify that the task has been completed or canceled.

2 future means that the task is completed forever in the completion state, just like the Executorservice life cycle. Use the Get method to complete tasks and exception handling.

3) All of the submit methods in Executorservice return a future that can submit a runnable or a callable to executor and then get a future. You can also explicitly instantiate a futuretask for a given runnable or callable.

Import java.util.concurrent.Callable;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

Import Java.util.concurrent.Future;
 /** * Callable and future interfaces * Callable similar runnable interfaces, classes that implement callable interfaces, and classes that implement runnable are tasks that can be performed by other threads.
 * There are several differences between callable and runnable: * (1) Callable The method specified is call (), and runnable the method specified is run (). 
 * (2) A callable task can return a value after execution, while a runnable task cannot return a value.
 * (3) The call () method throws an exception, and the run () method cannot throw an exception.
 * (4) Run callable task to get a future object, future represents the result of an asynchronous computation.
 * It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to retrieve the results of the calculation.
 * The Future object allows you to understand the execution of tasks, cancel the execution of the task, and get the results of the task execution. * * public class Callableandfuture {/** * Custom a task class, implement callable interface/public static class Mycallableclass implements C

		allable {//logo bit private int flag = 0;
		Public mycallableclass (int flag) {This.flag = flag;
			The public String called () throws Exception {if (This.flag = 0) {//If the flag value is 0, immediately returns return "flag = 0"; } if (This.flag = = 1) {//If flag value is 1, do an infinite loop try {while (true) {System.out.println ("looping ...");
					Thread.Sleep (2000);
				The catch (Interruptedexception e) {System.out.println ("interrupted");
			Return "false";
			else {//Falg is not 0 or 1, throws an exception throw new Exception ("Bad flag value!"); }} public static void Main (string[] args) {//define tasks for 3 callable types Mycallableclass Task1 = new Mycallableclass (0
		);
		Mycallableclass task2 = new Mycallableclass (1);

		Mycallableclass task3 = new Mycallableclass (2);
		Create a service that performs a task Executorservice es = Executors.newfixedthreadpool (3);
			try {//Commit and execute the task, the task starts with a Future object,//If you want the result of a task execution or an exception to manipulate the Future object Future future1 = Es.submit (TASK1);

			Gets the result of the first task, and if the Get method is called, the current thread waits for the task to execute before executing System.out.println ("Task1:" + future1.get ());
			Future Future2 = Es.submit (TASK2); Wait 5 seconds before stopping the second task.
			Because the second task carried out is an infinite cyclic thread.sleep (5000);

			System.out.println ("Task2 Cancel:" + Future2.cancel (true)); Gets the output of the third task because performing a third task causes an exception//So the following statement will cause an exception to be thrown Future future3 = Es.submit (TASK3);
		System.out.println ("TASK3:" + future3.get ());
		catch (Exception e) {System.out.println (e.tostring ());
	//Stop Task Execution Service Es.shutdownnow (); }
}

Run input results:

Task1:flag = 0
Looping ...
Looping ...
Looping ...
Task2 Cancel:true
Interrupted
Java.util.concurrent.ExecutionException:java.lang.Exception:Bad Flag value!

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.