java併發程式設計等待同步例項
阿新 • • 發佈:2018-12-15
java可以使用CountDownLatch來控制執行緒併發,使得一個或多個執行緒等待其他執行緒執行到某個操作後在執行。
如圖示:
1.在CountDownLatch例項化的時候定義需要等待的執行緒count數。
2.通過CountDownLatch的await方法,當count數為0時喚醒。
3.每次執行完需要先執行的執行緒時使用countDown方法,使得count數減1,就成功實現其他執行緒都執行完才執行await後操作
package study.joker.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.CountDownLatch; public class test1 { static Logger logger = LoggerFactory.getLogger(test1.class); public static void main(String[] args) { try { final CountDownLatch latch = new CountDownLatch(3); new Thread(() -> { try { logger.info("this is first Thread"); Thread.sleep(5000); latch.countDown(); logger.info("this is first end ;latch.count={}", latch.getCount()); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { logger.info("this is second Thread"); Thread.sleep(6000); latch.countDown(); logger.info("this is second end;latch.count={}", latch.getCount()); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { logger.info("this is third Thread begin"); Thread.sleep(7000); latch.countDown(); logger.info("this is third Thread end;latch.count={}", latch.getCount()); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); latch.await();//阻塞當前執行緒直到latch中數值為零才執行 // Thread.sleep(10); logger.info("主執行緒執行!latch.count={}", latch.getCount()); while (true) { } } catch (Exception e) { e.printStackTrace(); } } }