随笔- 191  文章- 0  评论- 3  阅读- 59455 

同步回调:

打印结果:
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   laremehpe  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示