CountDownLatch vs. Semaphore

6 浏览
0 Comments

CountDownLatch vs. Semaphore

在使用java.util.concurrent.CountdownLatch代替java.util.concurrent.Semaphore时,是否有任何优势?据我所知,以下片段几乎等效:

1. Semaphore:

final Semaphore sem = new Semaphore(0);

for (int i = 0; i < num_threads; ++ i)

{

Thread t = new Thread() {

public void run()

{

try

{

doStuff();

}

finally

{

sem.release();

}

}

};

t.start();

}

sem.acquire(num_threads);

2. CountDownLatch:

final CountDownLatch latch = new CountDownLatch(num_threads);

for (int i = 0; i < num_threads; ++ i)

{

Thread t = new Thread() {

public void run()

{

try

{

doStuff();

}

finally

{

latch.countDown();

}

}

};

t.start();

}

latch.await();

除了在情况2中无法重用latch,更重要的是您需要预先知道将创建多少个线程(或者在创建latch之前等待它们全部启动)。

那么,在什么情况下可能更适合使用latch呢?

0