Java騷操作之CountDownLatch代碼詳解
用來干嘛的?當你在方法中調(diào)用了多個線程,對數(shù)據(jù)庫進行了一些不為人知的操作后,還有一個操作需要留到前者都執(zhí)行完的重頭戲,就需要用到 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('此處對數(shù)據(jù)庫進行最后的插入操作~'); } 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() + '對數(shù)據(jù)庫進行插入,持續(xù)時間:' + this.times / 1000 + '秒');Thread.sleep(times);countDownLatch.countDown(); } catch (InterruptedException e) {e.printStackTrace(); } } }}圖解

使用await()提前結(jié)束操作
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() + '開始工作,持續(xù)時間:' + this.times / 1000 + '秒');countDownLatch.countDown(); } catch (InterruptedException e) {e.printStackTrace(); } } }}
假設(shè)公司一、公司二、公司三各需要2s、3s、5s來完成工作,賈總等不了,只能等2s,那么就設(shè)置await的超時時間
latch.await(2, TimeUnit.SECONDS);執(zhí)行結(jié)果
負責人:公司一開始工作,持續(xù)時間:2秒~~~賈總PPT巡演~~~~~~~~融資完成,撒花~~~~負責人:公司二開始工作,持續(xù)時間:3秒負責人:公司三開始工作,持續(xù)時間:5秒
方法描述

這個操作可以說是簡單好用,目前還未遇見副作用,若是有大佬,可以告知弟弟一下,提前表示感謝~
到此這篇關(guān)于Java騷操作之CountDownLatch的文章就介紹到這了,更多相關(guān)Java CountDownLatch內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 編程語言PHP在Web開發(fā)領(lǐng)域的優(yōu)勢在哪?2. 詳解Android studio 動態(tài)fragment的用法3. Android如何加載Base64編碼格式圖片4. Spring Boot和Thymeleaf整合結(jié)合JPA實現(xiàn)分頁效果(實例代碼)5. 解決Android studio xml界面無法預(yù)覽問題6. 什么是python的自省7. 基于android studio的layout的xml文件的創(chuàng)建方式8. .Net Core使用Coravel實現(xiàn)任務(wù)調(diào)度的完整步驟9. Springboot Druid 自定義加密數(shù)據(jù)庫密碼的幾種方案10. 圖文詳解vue中proto文件的函數(shù)調(diào)用

網(wǎng)公網(wǎng)安備