java常見的幾種調用機制(同步調用,異步調用,回調)

 

一、同步調用多線程

同步調用是最基本的調用方式,對象b中的方法直接調用對象a的方法,這個時候程序會等待對象a的方法執行完返回結果以後纔會繼續往下走。異步

代碼以下:ide

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");
}this

}spa

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

二、異步調用

對象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

說明:異步調用咱們一般採用多線程的方法來達到目的

三、回調

對象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抽象出一個接口出來,而後用實現類去實現着兩個接口,這樣代碼的擴展性會更好,也能知足更多的業務場景。

回調的核心在於:回調方將自己對象傳給調用方,調用方在自己代碼邏輯執行完以後,調用回調方的回調方法。

相關文章
相關標籤/搜索