Java Future Mode thread implementation asynchronous call (reprint)
In the multi-threaded interaction of 2, there are often one thread need to get another one of the calculation results, we often use the future asynchronous mode to solve.
Future as implies, a bit like the futures market "options", is "a voucher for the next", such as when we bought a real estate developer's off, pay the money, the developer will give us a voucher (option), this voucher tells us to take this voucher sometime next year to get the house we need, But now the house hasn't been built yet. There are "futures" in the market, and because of this demand, this kind of supply is available.
This kind of application is used more in GUI, it is commonly called "Virtual proxy mode" in design mode.
For example: Now that there is a requirement, client submits a request (int Count,char c) to the server and wants to get a string constructed of count characters c. For example, send request (K), then the feedback string "KKKKKKKKKK", but we assume that the process of generating a string is time-consuming.
So, in order to get good interactivity, after our server received the request, we first construct a futuredata, and the so-called "option (Future voucher)" Feedback to the client, at the same time, through another concurrent thread to construct a real string realdata, And after the construction, Realdata to futuredata report a message, said the data (plan) is ready, at this time, the client can get off the option, but if our client is more anxious, not waiting for the house fake good, want to house, how to do? This time we can block the client's thread, let the client wait, until the last realdata inform Futuredata said the house is good, only return.
Here's the point:
(1) The server first give the client an "option", while opening a thread to work the house son (the Future "existing");
(2) When the "existing" Realdata is ready, how to tell Futuredata that he is ready to do so. (This section uses the "callback process" (using the Observer pattern to implement the callback))
(3) If the customer is more anxious, the existing home is not ready, it is necessary to pick up the room, how to do? The department uses "blocking".
Data (public interface)
Java code
1.package com.umpay.future;
2.
3.public interface Data {
4. Public abstract String getcontent ();
5.}
Futuredata (option)
Java code
1.package Com.umpay.future.extend;
2.
3.import java.util.Observable;
4.import Java.util.Observer;
5.
6.import Com.umpay.future.Data;
7.
8.public class FutureData2 implements Data,observer {
9.
10.
-Private volatile RealData2 realData2 = null;
16.
. public Boolean isfinished () {
return REALDATA2! = NULL;
21.}
22.
23.
. Public String getcontent () {
Synchronized (mutex) {
while (!isfinished ()) {//block the calling thread as long as the data is not ready
. try {
Mutex.wait ();
.} catch (Interruptedexception e) {
E.printstacktrace ();
34.}
35.}
. return Realdata2.getcontent ();
37.}
38.}
39.
40.
public void Update (Observable realdata, Object event) {
SYSTEM.OUT.PRINTLN ("notice ...." +event);
. if (! ( Realdata instanceof RealData2)) {
A. throw new IllegalArgumentException ("The data type of the subject must be RealData2");
51.}
. if (! ( Event instanceof String)) {
A. throw new IllegalArgumentException ("The data type of the event must be string");
54.}
Synchronized (mutex) {
. if (isfinished ()) {
Mutex.notifyall ();
return;//. If the data is ready, return it directly.
59.}
if ("Finished". Equals (event)) {
RealData2 = (REALDATA2) realdata;//when the data is ready, you can tell the data to be ready.
Mutex.notifyall ();//Wake up a blocked thread
63.}
64.}
65.}
66.
The private object mutex = new Object ();
68.}
Realdata (actual data)
Java code
1.package Com.umpay.future.extend;
2.
3.import java.util.Observable;
4.
5.import Com.umpay.future.Data;
6.
7.public class RealData2 extends Observable implements Data {
8.
9. Private String content;
10.
One. Public RealData2 () {
12.
13.}
14.
. public void CreateRealData2 (int count, char c) {
System.out.println ("Making realdata (" + Count + "," + C
+ ") BEGIN");
char[] buffer = new Char[count];
for (int i = 0; i < count; i++) {
Buffer[i] = c;
. try {
Thread.Sleep (100);
.} catch (Interruptedexception e) {
24.}
25.}
System.out.println ("Making realdata (" + Count + "," + C
+ ") END");
This.content = new String (buffer);
29.
30.//Real data ready, notify FUTUREDATA2 that the data is ready.
Setchanged ()///must first set the state of this object to change and notify all observers
Notifyobservers ("finished");
33.}
34.
35.
. Public String getcontent () {
A. return content;
38.}
39.}
Service-Side code:
Java code
- Package com.umpay.future.extend;
- import Com.umpay.future.Data;
- Public class HostServer2 {
- Public Data Request (final int count, final char c) {
- SYSTEM.OUT.PRINTLN ("Request ( " + Count + "," + C + ") BEGIN");
- //(1) Establishment of futuredata entities
- Final FutureData2 future2 = new FutureData2 ();
- //(2) to create a realdata entity, start a new thread
- New Thread () {
- Public void Run () {
- RealData2 realdata2 = new RealData2 ();
- Realdata2.addobserver (Future2); //So that when REALDATA2 data is ready, through the callback, notify FUTUREDATA2 that the data has been stocked.
- Realdata2.createrealdata2 (count, c);
- }
- }.start ();
- SYSTEM.OUT.PRINTLN ("request (" + count + "," + C + ") END");
- //(3) retrieving the Futuredata entity as a return value
- return Future2;
- }
- }
Client code:
Java code
1.package com.umpay.future;
2.
3.import Com.umpay.future.extend.HostServer2;
4.
5.public class Mainclient {
6. public static void Main (string[] args) {
7.//Testhostserver ();
8. TestHostServer2 ();
9.}
10.
One. static void Testhostserver () {
System.out.println ("main BEGIN");
Hostserver hostserver = new Hostserver ();
Data data1 = Hostserver.request (, ' A ');
Data data2 = hostserver.request (+, ' B ');
Data data3 = hostserver.request (+, ' C ');
17.
System.out.println ("main otherjob BEGIN");
19.//try {
20.//Thread.Sleep (2000);
21.//} catch (Interruptedexception e) {
22.//}
System.out.println ("main otherjob END");
24.
System.out.println ("data1 =" + data1.getcontent ());
System.out.println ("data2 =" + data2.getcontent ());
System.out.println ("data3 =" + data3.getcontent ());
System.out.println ("main END");
29.
30.}
31.
. static void TestHostServer2 () {
System.out.println ("main BEGIN");
HostServer2 hostServer2 = new HostServer2 ();
Data data1 = Hostserver2.request (, ' A ');
Data data2 = hostserver2.request (+, ' B ');
PNs. Data data3 = hostserver2.request (+, ' C ');
38.
System.out.println ("main otherjob BEGIN");
40.//try {
41.//Thread.Sleep (2000);
42.//} catch (Interruptedexception e) {
43.//}
System.out.println ("main otherjob END");
45.
System.out.println ("data1 =" + data1.getcontent ());
System.out.println ("data2 =" + data2.getcontent ());
System.out.println ("data3 =" + data3.getcontent ());
System.out.println ("main END");
50.
51.}
52.}
Java Future Mode thread implementation asynchronous invocation (reprint