类似于前端中的Promise.race([p1,p2,p3...])
可以使用线程回调查看线程执行结果,有一个成功就成功。
package CountDownLatch;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchTest {
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(1);
for (int i = 0; i < 10; i++) {
es.submit(() -> {
try {
long wait = (long) (Math.random() * 1000);
Thread.sleep(wait);
System.out.println(wait);
latch.countDown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
// wait for the latch to be decremented by the fast threads
try {
latch.await();
System.out.println("Fast Thead End");
es.shutdownNow();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出:
49
Fast Thead End