In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the function of Callable, Future and FutureTask". In daily operation, I believe many people have doubts about the role of Callable, Future and FutureTask respectively. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "what are the functions of Callable, Future and FutureTask respectively?" Next, please follow the editor to study!
1.Callable interface
Let's review the java.lang.Runnable interface and declare run (), whose return value is void, and of course we can't get the result.
Public interface Runnable {
Public abstract void run ()
}
The interface definition of Callable is as follows
Public interface Callable {
V call () throws Exception
}
The interface declares a method named call (), which can either return a value V or throw an exception. Well, as long as we know so much about this interface, let's explain how to use it. As we said in the previous article, both the implementation class of Runnable interface and the implementation class of Callable interface can be executed by ThreadPoolExecutor or ScheduledThreadPoolExecutor, and both ThreadPoolExecutor and ScheduledThreadPoolExecutor implement the ExcutorService interface, so Callable needs to be used in conjunction with ExcutorService in the Executor framework. Let's first take a look at the methods provided by ExecutorService:
Future submit (Callable task)
Future submit (Runnable task, T result)
Future submit (Runnable task)
The first method: submit submits a task that implements the Callable interface and returns Future that encapsulates the result of the asynchronous calculation.
The second method: submit submits a task that implements the Runnable interface and specifies the result object that is returned when the get method of Future is called.
The third method: submit submits a task that implements the Runnable interface and returns Future that encapsulates the result of the asynchronous calculation.
So all we have to do is create our thread object (implement the Callable interface or the Runnable interface) and submit it to the thread pool for execution through the above three methods. It is also important to note that in addition to implementing the Callable object ourselves, we can also use the factory class Executors to wrap a Runnable object as a Callable object. The methods provided by the Executors factory class are as follows:
Public static Callable callable (Runnable task)
Public static Callable callable (Runnable task, T result)
2.Future interface
Future API is used to obtain asynchronous calculation results. To put it bluntly, it is to obtain (get ()) and cancel (cancel ()) the results of a specific Runnable or Callable object task, and determine whether the operation is completed or not. Let's look at the source code of the Future interface:
Public interface Future {
Boolean cancel (boolean mayInterruptIfRunning)
Boolean isCancelled ()
Boolean isDone ()
V get () throws InterruptedException, ExecutionException
V get (long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
}
Method parsing:
V get (): gets the result of asynchronous execution, and if no result is available, this method blocks until the asynchronous calculation is complete.
V get (Long timeout, TimeUnit unit): get the result of asynchronous execution. If no result is available, this method will block, but there will be a time limit. If the blocking time exceeds the set timeout time, this method will throw an exception.
Boolean isDone (): returns true if the task ends, whether it ends normally or cancels halfway or an exception occurs.
Boolean isCanceller (): returns true if the task is cancelled before the task is completed.
Boolean cancel (boolean mayInterruptRunning): if the task has not already started, execute cancel (...) Method will return false; if the task has been started, execute the cancel (true) method will attempt to stop the task by interrupting the execution thread of the task, if stopped successfully, return true; when the task has been started, execute the cancel (false) method will not affect the executing task thread (let the thread execute normally to complete), then return false; when the task has been completed, execute cancel (...) Method will return false. The mayInterruptRunning parameter indicates whether to interrupt the thread in execution.
Through the method analysis, we also know that Future actually provides three functions: (1) can interrupt the task in execution; (2) judge whether the task is completed or not; (3) obtain the post-completion result of task execution.
But we have to understand that Future is just an interface, and we can't create objects directly, so we need its implementation class FutureTask to debut.
3.FutureTask class
Let's first take a look at the implementation of FutureTask
Public class FutureTask implements RunnableFuture {
The FutureTask class implements the RunnableFuture interface. Let's take a look at the implementation of the RunnableFuture interface:
Public interface RunnableFuture extends Runnable, Future {
Void run ()
}
Analysis: FutureTask implements the Runnable interface in addition to the Future interface, so the FutureTask can also be submitted directly to Executor for execution. Of course, you can also call the thread to execute directly (FutureTask.run ()). Next, we analyze the three states of FutureTask.run () according to the timing of its execution:
(1) FutureTask is not started before the FutureTask.run () method is executed, and the FutureTask is not started when a FutureTask is created and the FutureTask.run () method is not executed.
(2) it has been started, and during the execution of FutureTask.run (), FutureTask is in the started state.
(3) after completion, the FutureTask.run () method ends normally, or it is cancelled or an exception is thrown, and the FutureTask is in the completion state.
Let's take a look at the method execution diagram of FutureTask (the method and Future interface are basically the same, which will not be described here)
Analysis:
(1) when FutureTask is in the unstarted or started state, if we execute the FutureTask.get () method at this time, the calling thread will block; when the FutureTask is in the completed state, executing the FutureTask.get () method will cause the calling thread to return the result immediately or throw an exception.
(2) when FutureTask is not started, executing the FutureTask.cancel () method will cause this task to never be executed.
When FutureTask is started, executing the cancel (true) method will attempt to stop the task by interrupting the thread executing the task. If the task is cancelled successfully, cancel (...) Return true; but if you execute the cancel (false) method will not affect the executing task thread (let the thread execute normally to finish), at this point cancel (.) Return to false.
When the task has been completed, execute cancel (...) Method will return false.
Finally, we give two constructors of FutureTask:
Public FutureTask (Callable callable) {
}
Public FutureTask (Runnable runnable, V result) {
}
The use of 3.Callable/Future/FutureTask
Through the above introduction, we have a clearer understanding of Callable,Future,FutureTask, so what is the use of them? As we said earlier, if we create a thread in this way, the greatest advantage is that we can return the result. With such a scenario, we now need to calculate a data, and the calculation of this data is time-consuming, and our later programs also need to use this data result, so isn't Callable the best choice at this time? We can set up a thread to perform the calculation, while the main thread continues to do other things, and when we need to use this data later, can't we just use Future to get it? Let's write an example like this.
3.1 use Callable+Future to get the execution result
The Callable implementation classes are as follows:
Package com.zejian.Executor
Import java.util.concurrent.Callable
/ * *
* @ author zejian
* @ time 2:02:42 15 March 2016
* @ decrition Callable API instance
, /
Public class CallableDemo implements Callable {
Private int sum
@ Override
Public Integer call () throws Exception {
System.out.println ("Callable child thread starts to calculate!")
Thread.sleep (2000)
For (int iInfo; i12497500)
The main thread is completing execution.
3.2Using Callable+FutureTask to get the execution result
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 2:05:43 15 March 2016
* @ decrition callable execute test class
, /
Public class CallableTest {
Public static void main (String [] args) {
/ create a thread pool
/ / ExecutorService es = Executors.newSingleThreadExecutor ()
/ create Callable object task
/ / CallableDemo calTask=new CallableDemo ()
/ / submit the task and get the execution result
/ / Future future = es.submit (calTask)
/ close the thread pool
/ / es.shutdown ()
/ / create a thread pool
ExecutorService es = Executors.newSingleThreadExecutor ()
/ / create Callable object task
CallableDemo calTask=new CallableDemo ()
/ / create a FutureTask
FutureTask futureTask=new FutureTask (calTask)
/ / perform the task
Es.submit (futureTask)
/ / close the thread pool
Es.shutdown ()
Try {
Thread.sleep (2000)
System.out.println ("main thread is performing other tasks")
If (futureTask.get ()! = null) {
/ / output the obtained results
System.out.println ("futureTask.get ()-- >" + futureTask.get ())
} else {
/ / output the obtained results
System.out.println ("futureTask.get () did not get the result")
}
} catch (Exception e) {
E.printStackTrace ()
}
System.out.println ("main thread is completing execution")
}
}
Execution result:
The Callable child thread starts to calculate!
The main thread is performing other tasks
The calculation of Callable child thread is over!
FutureTask.get ()-> 12497500
The main thread is completing execution.
At this point, the study on "what are the functions of Callable, Future and FutureTask respectively" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 204
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.