Parallel programming pattern-Future pattern

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);
    }
}

Client call:

@RestController
@RequestMapping(value = "/chat/app/test")
public class TestAppController {
    private FutureService futureService;
    private FutureClicent futureClicent;
    public TestAppController(FutureService futureService, FutureClicent futureClicent){
        this.futureService=futureService;
        this.futureClicent=futureClicent;
    }
     @PostMapping(value="test")
     public void Test(){
        deal("A",new int[]{1,2,3});
        deal("B",new int[]{7,8,2,3});
     }

     private void deal(String key,int[] b){
        new Thread(){
            @Override
            public void run() {
                FutureTask<String> futureTask=new FutureTask<String>(new FutureUtil(futureService,key,b));
                ExecutorService service= Executors.newFixedThreadPool(1);
                service.submit(futureTask);
                futureClicent.deal(key);
                try {
                    System.out.println(key+":处理完结果,返回主要业务逻辑结果:"+futureTask.get());
                    System.out.println(key+":结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }.start();
     }
}

Achieve results:

A:正在处理辅助辅助业务
B:正在处理辅助辅助业务
A:正在处理真实的业务逻辑
A:处理完结果,返回主要业务逻辑结果:6
A:结束
B:正在处理真实的业务逻辑
B:处理完结果,返回主要业务逻辑结果:20
B:结束

Guess you like

Origin blog.csdn.net/qq_28500837/article/details/105249028