一、类介绍
java.util.concurrent类CountDownLatch
public class CountDownLatch extends Object
一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。给定一个数来初始化CountDownLatch,这个值即需要等待的操作数。当某个线程需要等待一组操作时,通过调用await方法进行阻塞。某个操作完成,通过调用countDown方法使计数器减一。在该计数值到达0之前,调用await()方法的线程会一直等待。之后会释放所有等待的线程,await的后续调用将立即返回。该计数值无法被重置,即只能被初始化一次。
二、使用场景
-
将计数 1 初始化的 CountDownLatch 用作一个简单的开/关锁存器,或入口:在通过调用 countDown() 的线程打开入口前,所有调用 await 的线程都一直在入口处等待;
-
用 N 初始化的 CountDownLatch 可以使一个线程在 N 个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。
三、使用实例
1.等待者和任务者,一群等待者线程等待一群任务者线程完成任务。使用Countdownlatch控制等待者们等待,直到所有的任务者都完成它们的任务后,等待者才能执行。
package concurrent;
import java.util.concurrent.*;
import java.util.*;
import static net.mindview.util.Print.*;
// Performs some portion of a task:
class TaskPortion implements Runnable {
private static int counter = 0;
private final int id = counter++;
private static Random rand = new Random(47);
private final CountDownLatch latch;
TaskPortion(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
doWork();
latch.countDown();
} catch (InterruptedException ex) {
// Acceptable way to exit
}
}
public void doWork() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
print(this + "completed");
}
public String toString() {
return String.format("%1$-3d ", id);
}
}
// Waits on the CountDownLatch:
class WaitingTask implements Runnable {
private static int counter = 0;
private final int id = counter++;
private final CountDownLatch latch;
WaitingTask(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
latch.await();
print("Latch barrier passed for " + this);
} catch (InterruptedException ex) {
print(this + " interrupted");
}
}
public String toString() {
return String.format("WaitingTask %1$-3d ", id);
}
}
public class CountDownLatchDemo {
static final int SIZE = 10;
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();
// All must share a single CountDownLatch object:
CountDownLatch latch = new CountDownLatch(SIZE);
for (int i = 0; i < 5; i++)
exec.execute(new WaitingTask(latch));
/*创建100个任务线程,共享一个count为100的CountDownLatch,每个线程完成任务后执行countdown将count-1,直到count为0时,
* 即所有的线程都完成了任务,等待线程才能执行,因此,CountDownLatch可以很方便的等待一组线程完成任务*/
for (int i = 0; i < SIZE; i++)
exec.execute(new TaskPortion(latch));
print("Launched all tasks");
exec.shutdown(); // Quit when all tasks complete
}
} /* (Execute to see output) */// :~
上面的例子中创建了5个等待者线程和10个任务者线程。创建了一个初始值为10的CountdownLatch,5个等待者共享这个CountDownLatch,意思是他们共同等待一些操作,操作的个数为10.在每个操作中调用countDown()。所以10个任务者线程也共享这个CountDownLatch,每个线程完成任务后都调用了countDown,否则等待者们会一直等待。(注意:初始计数值的大小和任务者线程数要相同)
输出:
Launched all tasks
7 completed
8 completed
5 completed
9 completed
0 completed
3 completed
6 completed
4 completed
1 completed
2 completed
Latch barrier passed for WaitingTask 0
Latch barrier passed for WaitingTask 2
Latch barrier passed for WaitingTask 4
Latch barrier passed for WaitingTask 1
Latch barrier passed for WaitingTask 3
2.跑步比赛,所有的Player都必须等待听到枪响声后才能起跑。
package concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Player implements Runnable{
private CountDownLatch latch ;
public Player(CountDownLatch l) {
// TODO Auto-generated constructor stub
this.latch = l;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " start to run!");
}
}
class Guner implements Runnable{
private CountDownLatch latch ;
public Guner(CountDownLatch latch) {
super();
this.latch = latch;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0;i < 3;i++){
System.out.println(3-i);
}
System.out.println("Bong!");
latch.countDown();
}
}
public class CountDownLatchTest2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
CountDownLatch latch = new CountDownLatch(1);
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0;i < 8;i++){
exec.execute(new Player(latch));
}
exec.execute(new Guner(latch));
}
}
输出:
3
2
1
Bong!
pool-1-thread-1 start to run!
pool-1-thread-3 start to run!
pool-1-thread-8 start to run!
pool-1-thread-2 start to run!
pool-1-thread-4 start to run!
pool-1-thread-5 start to run!
pool-1-thread-6 start to run!
pool-1-thread-7 start to run!
三、重要方法
await
public void await()
throws InterruptedException
使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断。
如果当前计数为零,则此方法立即返回。
如果当前计数大于零,则出于线程调度目的,将禁用当前线程,且在发生以下两种情况之一前,该线程将一直处于休眠状态:
由于调用 countDown() 方法,计数到达零;或者
其他某个线程中断当前线程。
如果当前线程:
在进入此方法时已经设置了该线程的中断状态;或者
在等待时被中断,
则抛出 InterruptedException,并且清除当前线程的已中断状态。
抛出:
InterruptedException - 如果当前线程在等待时被中断
await
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException
使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。
如果当前计数为零,则此方法立刻返回 true 值。
如果当前计数大于零,则出于线程调度目的,将禁用当前线程,且在发生以下三种情况之一前,该线程将一直处于休眠状态:
由于调用 countDown() 方法,计数到达零;或者
其他某个线程中断当前线程;或者
已超出指定的等待时间。
如果计数到达零,则该方法返回 true 值。
如果当前线程:
在进入此方法时已经设置了该线程的中断状态;或者
在等待时被中断,
则抛出 InterruptedException,并且清除当前线程的已中断状态。
如果超出了指定的等待时间,则返回值为 false。如果该时间小于等于零,则此方法根本不会等待。
参数:
timeout - 要等待的最长时间
unit - timeout 参数的时间单位。
返回:
如果计数到达零,则返回 true;如果在计数到达零之前超过了等待时间,则返回 false
抛出:
InterruptedException - 如果当前线程在等待时被中断
countDown
public void countDown()
递减锁存器的计数,如果计数到达零,则释放所有等待的线程。
如果当前计数大于零,则将计数减少。如果新的计数为零,出于线程调度目的,将重新启用所有的等待线程。
如果当前计数等于零,则不发生任何操作。