基于大佬的例子进行接口改造:https://blog.csdn.net/it_freshman/article/details/80580369
烧一壶开水有如下几个步骤:
首先定义一个烧水接口:
- public interface BoilWater {
-
- void a_addWater() ;
-
- void b_on() ;
-
- void c_boiling() throws Exception ;
-
- void d_off() ;
-
- // 烧水方法
- void make() throws Exception;
-
- void playGame() throws Exception ;
-
- }
接下来我们对该接口进行实现,本次使用的是抽象类来实现该接口,这样make方法就可以不用具体的实现:
- public abstract class AbstractBoilWater implements BoilWater {
-
- protected volatile boolean isReadyFlag = false;
-
- @Override
- public void a_addWater() {
- System.out.println("1.加水");
- }
- @Override
- public void b_on() {
- System.out.println("2.打开煤气");
- }
- @Override
- public void c_boiling() throws Exception {
- System.out.println("3-1.烧水中.....");
- Thread.sleep(5000);
- System.out.println("3-2.水开了");
- isReadyFlag = true;
- }
- @Override
- public void d_off() {
- System.out.println("4.关闭煤气");
- }
-
- //烧水方法
- @Override
- public abstract void make() throws Exception;
- @Override
- public void playGame() throws Exception {
- Thread.sleep(1200);
- if (!isReadyFlag) {
- System.out.println("水还没烧开,玩一把游戏");
- }
- }
-
- }
接下来进行业务的调用,烧水没好的时候趁机打一把游戏,使用CompletableFuture继承AbstractBoilWater来进行异步调用和监听
- public class CompletableFutureBiolWater extends AbstractBoilWater {
- @Override
- public void make() throws Exception {
- a_addWater();
- b_on();
- CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
- try {
- c_boiling();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return 1;
- });
-
- //注册事件“监听”
- future.whenComplete((v, e) -> {
- System.out.println(v);
- System.out.println(e);
- d_off();
- });
-
- while (!future.isDone()) {
- playGame();
- }
- }
- }
编写测试类进行测试
- public class testMain {
- public static void main(String[] args) {
- CompletableFutureBiolWater completableFutureBiolWater= new CompletableFutureBiolWater();
- try {
- completableFutureBiolWater.make();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
效果如下:
备注,如果不止烧水这个过程,可能烧水和砍柴可以同时进行,那么可以改造成
- public class CompletableFutureBiolWater extends AbstractBoilWater {
- @Override
- public void make() throws Exception {
- a_addWater();
- b_on();
- CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
- try {
- c_boiling();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return 1;
- });
-
- //注册事件“监听”
- future.whenComplete((v, e) -> {
- System.out.println(v);
- System.out.println(e);
- d_off();
- });
- //模拟砍柴
- CompletableFuture<Integer> futurekanchai = CompletableFuture.supplyAsync(() -> {
- try {
- c_boiling();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return 2;
- });
-
- //注册事件“监听”
- futurekanchai.whenComplete((v, e) -> {
- System.out.println(v);
- System.out.println(e);
- d_off();
- });
-
- while (!future.isDone()&&!futurekanchai.isDone()) {
- playGame();
- }
- }
- }
引发了思考:在工单流程中,可能我们的一个订单其实都走好几个流程,这时候我们就可以使用异步流程的思路来进行设计,减少同步阻塞的时间;这里定义接口是为了方法进行接口的实现,当然也可以使用工程模式来进行优化