-
Scene: A classmate to the B classmates ask questions, B students need to do equation solution, and need a certain time, at this time a classmate can do their own things, to B students to complete the answer after the initiative to inform a classmate answer.
A classmate
1 Public classA {2B personb =NewB ();3 Public voidQuestionintINPUT1,intinput2) {4Personb.waitanswer (INPUT1, Input2,NewCallbacklistener () {5 @Override6 Public voidCallbackintresult) {7System. out. println ("B Answer:"+result);8 }9 });Ten One } A - Public Static voidMain (string[] args) { -A PersonA =NewA (); theSystem. out. println ("A to B question"); -Persona.question (1,2); -System. out. println ("I'm going to do something else before B tells me the answer."); - } +}View CodeB Students
1 Package callback;2 3 Public classB {4 Public voidWaitanswer (finalintA, finalintB,5 Final Callbacklistener Listener) {6 NewThread (NewRunnable () {7 @Override8 Public voidrun () {9 intc = A +b;Ten Listener.callback (c); One } A }). Start (); - } -}View CodeCallback Interface
1 Package callback; 2 3 Public Interface Callbacklistener {45 Public void callback (int result); 6 7 }
View Code
Java callback mechanism