In simple and simple multithreading (2) in the multi-threaded interaction, there is often a thread needs to get another first-line calculation results, we often use the future asynchronous mode to solve.
What is the future mode? Future, as the name suggests, in the financial sector called options, the market has put options and call options, you can now (for example, September) to buy oil at the end (December), if you are buying a call option, then if the oil is really up, you can also in December according to the price agreed in September. Pull away, future is the result you can get in the future. For multiple threads, if thread a waits for the result of thread B, thread A does not have to wait for B until B has a result, can get a future future, and so on B has the result is to take the real result. In fact, this model used a lot, such as the browser download pictures, just at the beginning is not the picture to replace the last picture, such as downloading pictures of the thread after downloading the picture in the replacement. As shown in the figure:
In the absence of the concurrent provided by JDK1.5, we are responsible for the result holding by customizing a result class.
Like the following code:
package vincent.blogjava.net;
public class FutureResult {
private String result;
private boolean isFinish =false;
public String getResult() {
return result;
}
public synchronized void setResult(String result) {
this.result = result;
this.isFinish = true;
}
public synchronized boolean isFinish() {
return isFinish;
}
}
Flag that stores the result value and whether it is completed.
package vincent.blogjava.net;
public class GenerateResultThread extends Thread{
FutureResult fr ;
public GenerateResultThread(FutureResult fr ){
this.fr = fr;
}
public void run(){
//模仿大量耗时计算后(5s)返回结果。
try {
System.out.println("GenerateResultThread开始进行计算了! ");
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fr.setResult("ResultByGenerateResultThread");
}
}