2019-08-14

目录

回调
使用wait和notify方法实现异步回调
使用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("主线程内容");
    }
}
View Code

相关文章: