小編給大家分享一下Java中CountDownLatch怎么用,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都做網(wǎng)站、成都網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的中寧網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
用來干嘛的?當(dāng)你在方法中調(diào)用了多個(gè)線程,對(duì)數(shù)據(jù)庫(kù)進(jìn)行了一些不為人知的操作后,還有一個(gè)操作需要留到前者都執(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("此處對(duì)數(shù)據(jù)庫(kù)進(jìn)行最后的插入操作~");
}
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()
+ "對(duì)數(shù)據(jù)庫(kù)進(jìn)行插入,持續(xù)時(shí)間:" + this.times / 1000 + "秒");
Thread.sleep(times);
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
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("負(fù)責(zé)人:" + Thread.currentThread().getName()
+ "開始工作,持續(xù)時(shí)間:" + this.times / 1000 + "秒");
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
假設(shè)公司一、公司二、公司三各需要2s、3s、5s來完成工作,賈總等不了,只能等2s,那么就設(shè)置await的超時(shí)時(shí)間
latch.await(2, TimeUnit.SECONDS);
執(zhí)行結(jié)果
負(fù)責(zé)人:公司一開始工作,持續(xù)時(shí)間:2秒
~~~賈總PPT巡演~~~~
~~~~融資完成,撒花~~~~
負(fù)責(zé)人:公司二開始工作,持續(xù)時(shí)間:3秒
負(fù)責(zé)人:公司三開始工作,持續(xù)時(shí)間:5秒
看完了這篇文章,相信你對(duì)“Java中CountDownLatch怎么用”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!