2019-08-14java
1 回調
2 使用wait和notify方法實現異步回調
3 使用CountDownLatch實現異步回調異步
返回async
回調的思想是:ide
返回this
ICallback代碼:spa
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代碼:code
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("主線程內容"); } }
返回blog
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("主線程內容"); } }