异步回调
异步回调
2019-08-14
1 回调
2 使用wait和notify方法实现异步回调
3 使用CountDownLatch实现异步回调
1 回调
回调的思想是:
- 类A的a()方法调用类B的b()方法
- 类B的b()方法执行完毕主动调用类A的callback()方法
2 使用wait和notify方法实现异步回调
ICallback代码:
public interface ICallback { void callback(long response); }
AsyncCallee代码:
import java.util.Random; public class AsyncCallee { private Random random = new Random(System.currentTimeMillis()); public void doSomething(ICallback iCallback){ new Thread(()->{ long res = random.nextInt(4); try { Thread.sleep(res*1000); } catch (InterruptedException e) { e.printStackTrace(); } iCallback.callback(res); }).start(); } }
Caller1代码:
public class Caller1 implements ICallback{ private final Object lock = new Object(); AsyncCallee callee; public Caller1(AsyncCallee asyncCallee){ callee=asyncCallee; } public void callback(long response) { System.out.println("得到结果"); System.out.println(response); System.out.println("调用结束"); synchronized (lock) { lock.notifyAll(); } } public void call(){ System.out.println("发起调用"); callee.doSomething(this); System.out.println("调用返回"); } public static void main(String[] args) { AsyncCallee asyncCallee=new AsyncCallee(); Caller1 demo1 = new Caller1(asyncCallee); demo1.call(); synchronized (demo1.lock){ try { demo1.lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("主线程内容"); } }
3 使用CountDownLatch实现异步回调
import java.util.concurrent.CountDownLatch; public class Caller2 implements ICallback{ private final CountDownLatch countDownLatch = new CountDownLatch(1); AsyncCallee callee; public Caller2(AsyncCallee asyncCallee){ callee=asyncCallee; } @Override public void callback(long response) { System.out.println("得到结果"); System.out.println(response); System.out.println("调用结束"); countDownLatch.countDown(); } public void call(){ System.out.println("发起调用"); callee.doSomething(this); System.out.println("调用返回"); } public static void main(String[] args) { AsyncCallee asyncCallee=new AsyncCallee(); Caller2 demo4 = new Caller2(asyncCallee); demo4.call(); try { demo4.countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("主线程内容"); } }