>>分享Java编程技术,对《Java面向对象编程》等书籍提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 21736 个阅读者 刷新本主题
 * 贴子主题:  java常见的几种调用机制:同步调用,异步调用,回调 回复文章 点赞(0)  收藏  
作者:flybird    发表时间:2020-02-06 18:07:03     消息  查看  搜索  好友  邮件  复制  引用

                                                                              
        1、同步调用

         同步调用是最基本的调用方式,对象b中的方法直接调用对象a的方法,这个时候程序会等待对象a的方法执行完返回结果之后才会继续往下走。

         代码如下:
public class A {

  public void methodA(){

    System.out.println("this is class A method");

  }

}

public class B {

  public void methodB()

  {

    A a = new A();

    a.methodA();

    System.out.println("this is class B method");

  }

}

public class Test {

   public static void main(String[] args) {

      B b = new B();

      b.methodB();

   }

}

         结果:

         this is class A method

         this is class B method

         2、异步调用

         对象b中的方法调用对象a的方法,程序并不需要等待对象a的方法返回结果值,直接继续往下走。

         代码如下:


public class A extends Thread{

  @Override

  public void run() {

     try {

        Thread.sleep(3000);

      } catch (InterruptedException e) {

          e.printStackTrace();

      }

      System.out.println("this is class A method");

   }

}

public class B {

   public void methodB()
   {
  
      A a = new A();

     a.start();

     System.out.println("this is class B method");

   }

}

public class Test {

    public static void main(String[] args) {

        B b = new B();

        b.methodB();

   }

}

         结果:

         this is class B method

         this is class A method

         说明:异步调用我们通常采用多线程的方法来达到目的

         3、回调

         对象a的方法methodA()中调用对象b的methodB()方法,在对象b的methodB()方法中反过来调用对象a的callBack()方法,这个callBack()方法称为回调函数,这种调用方法称为回调。

         代码如下:


public class A {

   public void methodA()
   {

      B b = new B();

      b.methodB(new A());

      System.out.println("this is class A method : methodA");

   }

   public void callBack()
   {

      System.out.println("this is class A method : callBack");

   }

}

public class B {

  public void methodB(A a)
  {

     System.out.println("this is class B method : methodB");

    a.callBack();

  }

}

public class Test {

   public static void main(String[] args) {

       A a = new A();

      a.methodA();

   }

}

         运行结果:

         this is class B method : methodB

         this is class A method : callBack

         this is class A method : methodA

         注意:这里如果为了代码的扩展性更好,可以把类A与类B抽象出一个接口出来,然后用实现类去实现着两个接口,这样代码的扩展性会更好,也能满足更多的业务场景。

         回调的核心在于:回调方将本身对象传给调用方,调用方在本身代码逻辑执行完之后,调用回调方的回调方法。
                                    
                                                
----------------------------
原文链接:https://blog.csdn.net/zhenwei1994/article/details/79615861

程序猿的技术大观园:www.javathinker.net



[这个贴子最后由 flybird 在 2020-02-06 21:24:20 重新编辑]
网站系统异常


系统异常信息
Request URL: http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=2569

java.lang.NullPointerException

如果你不知道错误发生的原因,请把上面完整的信息提交给本站管理人员