同步回调:

打印结果:
1
2
3

    public interface Result {
        void callBack();
    }

    public static void main(String[] args) throws InterruptedException {
        Entity entity = new Entity();
        entity.task(() -> System.out.println("2"));
        System.out.println("3");
    }

    public class Entity {
        public void task(Result cb){
            try {
                Thread.sleep(3000);
                System.out.println("1");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            cb.callBack();
        }
    }

异步回调:

打印结果:
1
2
3

和上面唯一的不同点在于

new Thread(()->{
entity.task(() -> System.out.println("3"));
}).start();

    public interface Result {
        void callBack();
    }

    public static void main(String[] args) throws InterruptedException {
        Entity entity = new Entity();
        new Thread(()->{
            entity.task(() -> System.out.println("3"));
        }).start();
        System.out.println("1");
    }

    public class Entity {
        public void task(Result cb){
            try {
                Thread.sleep(3000);
                System.out.println("2");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            cb.callBack();
        }
    }

 posted on 2023-04-14 13:36  laremehpe  阅读(37)  评论(0编辑  收藏  举报