个人理解就是A函数调用B函数后,B再通过调用A的接收方法将结果返回给A。
场景应用:
假设Tom去书店买书,由于书店的书比较多,店员不能立即找到,而Tom还有其他事要做,所以Tom就留下联系方式给了店员,让店员找到书后立即通知Tom。
其中“店员找到书后立即通知Tom”就是属于回调。
Tom: I want to buy a book. When you find it,call me.
Tom walked out....
Jack: I want to buy a book. When you find it,call me.
BookStore: checking Tom's books...
Jack walked out....
BookStore: checking Jack's books...
BookStore: I find the book,I will infomation--->Tom
BookStore: I find the book,I will infomation--->Jack
Jack: I got the infomation "BookStore: I hava your book." from the bookstore.
Tom: I got the infomation "BookStore: I hava your book." from the bookstore.
Tom: I bought a book.
Jack: I bought a book.
附上源码:
package CallBack;
public interface CallBack {
public void callBack(String info);
}
package CallBack;
public class Customer implements CallBack{
private BookStore bookStore;
private String custName;
public Customer(String custName,BookStore bookStore) {
this.bookStore = bookStore;
this.custName = custName;
}
public String getCustName() {
return custName;
}
public void buyBook() {
System.out.println(custName +": I want to buy a book. When you find it,call me.");
new Thread(new Runnable() {
@Override
public void run() {
try {
checkBook();
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
).start();
System.out.println(custName+" walked out....");
}
public void checkBook() {
bookStore.checkBook(this);
}
@Override
public void callBack(String info) {
System.out.println(custName +": I got the infomation \""+info+"\" from the bookstore.");
System.out.println(custName +": I bought a book.");
}
}
package CallBack;
public class BookStore {
public void checkBook(Customer customer) {
System.out.println("BookStore: checking "+ customer.getCustName() +"\'s books...");
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
info(customer);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
).start();
}
public void info(Customer customer) {
System.out.println("BookStore: I find the book,I will infomation--->"+ customer.getCustName());
customer.callBack("BookStore: I hava your book.");
}
}
package CallBack;
public class CallbackTest {
public static void main(String[] args) {
BookStore bookStore = new BookStore();
Customer customer1 = new Customer("Tom",bookStore);
Customer customer2 = new Customer("Jack",bookStore);
customer1.buyBook();
customer2.buyBook();
}
}
以上纯属个人见解,欢迎讨论~