问题来自
https://ask.csdn.net/questions/7413376?spm=1005.2025.3001.5141
JAVA中只要有一个线程执行成功,就算执行成功 如何写代码
-
java
类似于前端中的Promise.race([p1,p2,p3...])
使用CountDownLatch
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();
}
}
}
119
Fast Thead End