Scenario: Thread A needs the execution result of thread B, but there is no need to wait for thread B to finish, this time we can get the future object, and wait for the end of thread B to take the real result. Defines realdata real data classes whose constructors are slow and are the last data a user needs to use.
Static Classrealdata<T> {
protectedTresult;
PublicRealdata (TResult) {
This.result= Result;
}
PublicTGetResult() {
returnresult;
}
}
Defining the Future Object task class, which is the key of the future mode, is the proxy of the real data realdata, encapsulating the waiting process of acquiring realdata.
Public classfuturedata<T> {
private static FinalUtilslogLG= Utilslog.GetLogger(Futuredata.class);
protected BooleanIsReady=false;
Privaterealdata<T>Realdata=null;
PrivateObjectMutix=NewObject ();
Public StaticFuturedataRequest(FinalString request) {
LG. E ("New Futuredata object");
FinalFuturedata future =NewFuturedata ();
NewThread (NewRunnable () {
@Override
Public voidRun() {
Utilsthread.sleepignoreinteruptedexception( the);
LG. E ("************* analog time consuming thread with time:5000******");
Realdata Realdata =NewRealdata (Request);
Future. Setrealdata (Realdata);
}
}). Start ();
LG. E ("return new Futuredata Object");
returnFuture;
}
PublicTGetResult() {
synchronized(Mutix) {
while(!IsReady) {
LG. E ("Getresult:before Wait");
Try{
Mutix. Wait ();
}Catch(Interruptedexception e) {
E.printstacktrace ();
}
LG. E ("Getresult:after Wait");
}
LG. E ("GetResult:"+Realdata. GetResult (). toString ());
returnRealdata. GetResult ();
}
}
Public voidSetrealdata(realdata<T> Realdata) {
LG. E ("Execution Settings data: Setrealdata");
if( This.IsReady) {
return;
}
This.Realdata= Realdata;
This.IsReady=True
synchronized(Mutix) {
Mutix. Notify ();
}
}
}
initiates a request at the business layer and calls the GetResult method to wait for the return task execution result.
Futuredata futuredata = Futuredata. Request ("I want to perform time-consuming tasks") ;
LG. E (+ futuredata.getresult ());
The results of the operation are as follows, and if Isready=false is called by the GetResult method, the current thread is locked until notify () is called in Setrealdata and the method after wait is resumed.
For the wait for object and the relevant knowledge points for notify, see the method parsing of wait and notify for Java object
From for notes (Wiz)
Future patterns in Java's multi-threading