我自己对于基本回调函数的理解
回调函数需要两个类和一个接口来实现
C接口中定义B类完成后,调用的A中方法
A类实现C接口,且调用B类方法
B类中被调用的方法参数是C接口
我认为回调函数主要应该就是说的那个接口中定义的方法,B类能根据规定的回调方法,约定俗成的调用A的工作流程。
测试过程
A调用B方法,B获得这个A,B调用A的接口方法。
我自己的升级实现
代码解释:
商店对象是一个多线程,每天都在开店子,卖商品,关店子。一直运行。
用户对象只购买一次shop的商品,shop的商品如果没有则第二天首先出售此用户,如果有则直接出售给此用户。
public class Demo { public static void main(String[] args) { //去商店买东西 Shop s = new Shop(); Person p = new Person("小明"); //商店东西没了,记录这个用户 //商店东西有了,告诉这个用户 Thread threadShop = new Thread(s); threadShop.start(); try { Thread.currentThread().sleep(3000); p.buy(s); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class Person implements CallBack{ private String name; public Person(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void buy(Shop s) { System.out.println(name + "买东西去了"); s.Buy(this); } @Override public String toString() { return "Person [name=" + name + "]"; } @Override public void doSomething() { System.out.println(name + "东西买到了,我要走了"); } } interface CallBack{ public void doSomething(); } class Shop implements Runnable { private int count; private Person obj; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public void open() { this.count = 3; System.out.println(Thread.currentThread().getName() + "---------新的一天--------"); System.out.println("开张了,东西还有" + this.count); } public void sale() { System.out.println("出售一个商品,还剩" + --this.count); } public void close() { System.out.println("关门了,东西没有了" + this.count); } public void Buy(Person p) { if (count == 0) { System.out.println("商品卖完了,我做一会儿"); obj = p; }else { System.out.println("有商品"); count--; p.doSomething(); } } @Override public String toString() { return "Shop [count=" + count + "]"; } @Override public void run() { // TODO Auto-generated method stub while(true) { try { open(); if (obj != null) { //先满足上一个客人的订单 count--; obj.buy(this); obj = null; } while(this.count != 0) { sale(); Thread.currentThread().sleep(1000); } close(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }