Java asynchronous call 1

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 Futurerelated blog.

By Futurecalling 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.

FutureTaskIt is Futurean 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 Callableto implement.

FutureTask7 states, where the value from small to large:
NEW COMPLETING NORMAL EXCEPTIONAL CANCELLED INTERRUPTING INTERRUPTED
wherein, there are several possible transfer status mode:

  1. New -> completion -> General
  2. New -> completion -> Exception
  3. New -> Canceled
  4. 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

FutureTaskThe constructors pass in a Callablesubject, and it Runnable's the main difference is:

Callable Runnable
Realization callmethod Realization runmethod
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.

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
      
      
ExecutorService executorService = Executors.newFixedThreadPool( 5);
// asynchronous objects were created five corresponding
FutureTask<JSONObject> generalA = getGeneral(receiver, MessageType.A);
FutureTask<JSONObject> generalB = getGeneral(receiver, MessageType.B);
FutureTask<JSONObject> generalC = getGeneral(receiver, MessageType.C);
FutureTask<JSONObject> generalD = getGeneral(receiver, MessageType.D);
FutureTask<JSONObject> generalE = getGeneral(receiver, MessageType.E);
// to five asynchronous execution objects
executorService.execute(generalA);
executorService.execute(generalB);
executorService.execute(generalC);
executorService.execute(generalD);
executorService.execute(generalE);
//获取到五个对应的异步结果,时间取决于最慢的一个异步方法
try {
response.put( "a_result", generalA.get());
response.put( "b_result", generalB.get());
response.put( "c_result", generalC.get());
response.put( "d_result", generalD.get());
response.put( "e_result", generalE.get());
return response;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
//在所有结束情形下关闭线程池,回收资源
executorService.shutdown();
}

下面是getGeneral的代码:

      
      
1
2
3
4
5
6
7
8
9
      
      
private FutureTask<JSONObject> (String receiver, MessageType messageType) {
return new FutureTask<JSONObject>( new Callable<JSONObject>() {
public JSONObject call() throws Exception {
//Do Something ....
return messageJson;
}
});
}

这样就完成了我们的五组异步调用.


异步方面我暂且也学到这里,将来有机会继续更新有关异步的内容.

原文:大专栏  Java异步调用1


Guess you like

Origin www.cnblogs.com/petewell/p/11615063.html