本篇文章給大家分享的是有關Java中CountDownLatch的作用有哪些,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
package com.github.gleans; import java.util.concurrent.CountDownLatch; public class TestCountDownLatch { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); new KeyPass(1000L, "thin jack", latch).start(); new KeyPass(2000L, "noral jack", latch).start(); new KeyPass(3000L, "fat jack", latch).start(); latch.await(); System.out.println("此處對數據庫進行最后的插入操作~"); } static class KeyPass extends Thread { private long times; private CountDownLatch countDownLatch; public KeyPass(long times, String name, CountDownLatch countDownLatch) { super(name); this.times = times; this.countDownLatch = countDownLatch; } @Override public void run() { try { System.out.println("操作人:" + Thread.currentThread().getName() + "對數據庫進行插入,持續時間:" + this.times / 1000 + "秒"); Thread.sleep(times); countDownLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
使用await()提前結束操作
package com.github.gleans; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class TestCountDownLatch { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); new KeyPass(2000L, "公司一", latch).start(); new KeyPass(3000L, "公司二", latch).start(); new KeyPass(5000L, "公司三", latch).start(); latch.await(2, TimeUnit.SECONDS); System.out.println("~~~賈總PPT巡演~~~~"); System.out.println("~~~~融資完成,撒花~~~~"); } static class KeyPass extends Thread { private long times; private CountDownLatch countDownLatch; public KeyPass(long times, String name, CountDownLatch countDownLatch) { super(name); this.times = times; this.countDownLatch = countDownLatch; } @Override public void run() { try { Thread.sleep(times); System.out.println("負責人:" + Thread.currentThread().getName() + "開始工作,持續時間:" + this.times / 1000 + "秒"); countDownLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
假設公司一、公司二、公司三各需要2s、3s、5s來完成工作,賈總等不了,只能等2s,那么就設置await的超時時間
latch.await(2, TimeUnit.SECONDS);
以上就是Java中CountDownLatch的作用有哪些,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。