java CountDownLatch 控制異步和同步

應用場景舉例:java

  執行A項目的方法,須要調用B項目、C項目、D項目的接口方法。redis

需求:緩存

  異步調用B、C、D項目的接口方法,且每一個接口都調用結束後,A項目的方法才能夠結束。異步

注:若是須要獲取接口返回結果,可使用緩存(key,value)保存。線程只支持線程外的靜態參數傳遞,不嚴謹。async

package com.sze.redis.async; import java.util.concurrent.CountDownLatch; public class AsyncTest { public static void main(String[] args) throws InterruptedException { System.out.println("<=================A項目方法開始==============>"); CountDownLatch latch = new CountDownLatch(3); Thread B = new Thread(new Runnable() { @Override public void run() { System.out.println("B項目接口調用===開始"); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("B項目接口調用===結束"); latch.countDown(); } }); Thread C = new Thread(new Runnable() { @Override public void run() { System.out.println("C項目接口調用===開始"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("C項目接口調用===結束"); latch.countDown(); } }); Thread D = new Thread(new Runnable() { @Override public void run() { System.out.println("D項目接口調用===開始"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("D項目接口調用===結束"); latch.countDown(); } }); System.out.println("B C D start"); B.start(); C.start(); D.start(); latch.await(); System.out.println("<=================A項目方法結束==============>"); } }

結果ide

<=================A項目方法開始==============>
B C D start
B項目接口調用===開始
D項目接口調用===開始
C項目接口調用===開始
D項目接口調用===結束
C項目接口調用===結束
B項目接口調用===結束
<=================A項目方法結束==============>
相關文章
相關標籤/搜索