Definition: The Future model is similar to a product order. After the customer places an order, the seller needs a lot of time to prepare the product and the logistics and distribution process. During this time, the customer can do other things first, and then process the order after receiving the order;
Case: Future mode implemented in JDK, FutureTask class
Code:
Main business (long time-consuming):
@Service
public class FutureService{
public String dealRealData(String key,int[] data) throws InterruptedException {
//耗时较长
Thread.sleep(1000);
System.out.println(key+":正在处理真实的业务逻辑");
int a=0;
for(int i=0,len=data.length;i<len;i++){
a=a+data[i];
}
return a+"";
}
}
Auxiliary business, not related to main business data
@Service
public class FutureClicent {
public void deal(String key){
//再真实业务处理时,可以在等待主要业务进行的同时,先干点其他的事
System.out.println(key+":正在处理辅助辅助业务");
}
}
Main business agent tool
public class FutureUtil implements Callable {
private FutureService futureService;
private String key;
private int[] data;
public FutureUtil(FutureService futureService,String key,int[] data){
this.futureService=futureService;
this.key=key;
this.data=data;
}
@Override
public Object call() throws Exception {
//处理真是业务逻辑
return futureService.dealRealData(key,data);
}
}