多執行緒 CountDownLatch 使用
阿新 • • 發佈:2018-12-16
執行緒 CountDownLatch 用法
說明
CountDownLatch 用法簡述:
- CountDownLatch,一個同步輔助類,在完成一組正在其他執行緒中執行的操作之前,它允許一個或多個執行緒一直等待
- **countDown方法,當前執行緒結束執行後呼叫,計數減一 **
- **awaint方法,呼叫此方法會一直阻塞當前執行緒,直到計時器的值為0 **
程式碼,例如:
public class CountDownLatchDemo {
final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
final static String startTime = sdf.format(new Date());
public static void main(String[] args) throws InterruptedException {
//併發: CountDownLatch 它允許一個或多個執行緒一直等待,直到其他執行緒的操作執行完後再執行
CountDownLatch latch = new CountDownLatch(2);// 兩個賽跑者
Runer runer1 = new Runer("劉翔", 2000, latch);
Runer runer2 = new Runer("羅伯斯", 5000, latch);
runer1.start();// 劉翔 開始跑步
runer2.start();// 羅伯斯 開始跑步
latch.await();// 等待所有人賽跑結束
System.out.println("all runer done at " + sdf.format(new Date()));
}
static class Runer extends Thread {
String runerName;
int runTime;
CountDownLatch latch;
public Runer(String runerName, int runTime, CountDownLatch latch) {
this.runerName = runerName;
this.runTime = runTime;
this.latch = latch;
}
public void run() {
System.out.println("Runer " + runerName + " do run begin at " + startTime);
doRun();// 跑步
System.out.println("Runer " + runerName + " do run complete at " + sdf.format(new Date()));
latch.countDown();// 終點結束,計數器減一
}
private void doRun() {
try {
Thread.sleep(runTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}