public interface CallBack { public void solve(String result); }
public class Wang implements CallBack { public String result; private Li li; public Wang(Li li) { this.li = li; } @Override public void solve(String result) { this.result = result; System.out.println("the result is : -->" + result); } public void askQuestion(final String question) { new Thread(new Runnable() { @Override public void run() { li.executeMessage(Wang.this, question); } }).start(); play(); } public void play() { System.out.println("I am go shopping."); } }
public class Li { public void executeMessage(CallBack callBack, String question) { System.out.println("xiao wang's question? -->" + question); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } String result = "the answer is 2"; callBack.solve(result); } }
public class Client { public static void main(String []args) { Li li = new Li(); Wang wang = new Wang(li); wang.askQuestion("1 + 1 = ?"); System.out.println("after shopoing : ->" + wang.result); } }