zoukankan      html  css  js  c++  java
  • java的回调

    java的回调

    1,明确什么是回调方法

    2,采用接口来实现回调

    java同步回调 

    一个类实现了接口,将他传递给另一个类,在另一个类调用接口中方法

    public class Bar implements Foo.FooCallback {
    
        public void eatFood() {
            System.out.println("in eatFood() ");
        }
    
        //这是回调方法
        @Override
        public void eat(String food) {
            System.out.println("【@】" + food);
        }
    
    }
    public class Foo{
        
       public FooCallback fooCallback;
    
       public Foo(FooCallback fooCallback) {
           this.fooCallback = fooCallback;
       }
       
       public interface FooCallback{
           public void eat(String food);
       }
       
       public void say() {
           fooCallback.eat("西安蛋炒饭");
       }
       
    }
    public class demo {
        public static void main(String args[]) {
            Bar bar = new Bar();
            Foo foo = new Foo(bar);
            foo.say();
        }
    }

    java异步回调

    其实和同步回调差不多,只是新开线程,然后在新线程中回调接口中的方法

    public interface EatRice {
       public void eat(String food);
    }
    public class XiaoMing implements EatRice {
    
        public void say() {
    
        }
    
        @Override
        public void eat(String food) {
            System.out.print("小明和小李一起去吃" + food);
        }
    }
    public class XiaoLi {// 小李
    
        protected EatRice er;
    
        public void setEatRiceListener(EatRice er, String food) {
            this.er = er;
            washFace(food);
        }
    
        public void washFace(String food) {
    
            System.out.print("小李要洗漱");
    
            new Thread(new Runnable() {
    
                @Override
                public void run() {
                    try {
                        // 小李洗漱的同时小明玩手机,开启线程实现异步
                        play();
                        
                        Thread.sleep(10000);
                        System.out.print("10秒后 ");
                        // B调用A的方法
                        er.eat(food);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    
        public void play() {
            System.out.println(" 小明要玩手机");
        }
    
    }
        public static void main(String[] args) {
            
            EatRice er = new XiaoMing();
            new XiaoLi().setEatRiceListener(er, "小龙虾");
        }
  • 相关阅读:
    Codeforces Round #411 (Div. 2)
    腾讯比赛资料
    AtCoder Beginner Contest 060
    hdu 5288 数学 ****
    hdu 1866 几个矩形面积的和 ***
    hdu 2232 矩阵 ***
    bzoj 1415 期望+记忆化搜索 ****
    hdu 5033 单调栈 ****
    hdu 3032 sg打表找规律 *
    hdu 2516 FIB博弈
  • 原文地址:https://www.cnblogs.com/moris5013/p/10691588.html
Copyright © 2011-2022 走看看