Among our use of Scala process. We will use frequently a class method called asynchronous method .
In Scala is the most familiar to us scala.concurrent.Future
. Do not understand the relevant content can see Future
related blog.
By Future
calling the method, we can particularly elegant way to achieve asynchronous calls. Which is similar to using multiple threads.
In Java, most of the code is executed synchronously. Simply put, that is, I'll make a meal backboard, then wash rice. rice and other cooked vegetables stir-fry dishes a go hold rice dishes for vegetables put the table for dinner.
With asynchronous methods, we can do first scrubbing pots dishwashing, wash rice cooking in the effort to free vegetables stir-fry cooking. Greatly reduce the efficiency of our program.
FutureTask
It is Future
an implementation of the interface class, which is introduced from the beginning Java 1.5 by its ability to control the behavior of which it is carried. Specific contents through Callable
to implement.
FutureTask
7 states, where the value from small to large:NEW
COMPLETING
NORMAL
EXCEPTIONAL
CANCELLED
INTERRUPTING
INTERRUPTED
wherein, there are several possible transfer status mode:
- New -> completion -> General
- New -> completion -> Exception
- New -> Canceled
- New -> break in -> interrupted
FutureTask
There are many ways, including:
isCancelled
Method: Returns whether canceled (when the state is the last three cases)isDone
Method: Returns whether the process (when the state is not new)cancel
Methods: The method attempts to cancel (the state might become canceled or interrupted)get
Methods: to get the return value, if passed in time and overtime, then it will throw an exception
FutureTask
The constructors pass in a Callable
subject, and it Runnable
's the main difference is:
Callable |
Runnable |
---|---|
Realization call method |
Realization run method |
The results obtained to return | The results can not be obtained directly |
You can throw an exception | Not throw |
Next we look at the code directly realized;
First, I have a method to obtain information corresponding to the five getGeneral
.
|
|
下面是getGeneral
的代码:
|
|
这样就完成了我们的五组异步调用.
异步方面我暂且也学到这里,将来有机会继续更新有关异步的内容.