三个天气服务商,看那个返回的快用哪个
import lombok.SneakyThrows;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
public class HXWait {
public static void main(String[] args) throws ExecutionException, InterruptedException {
final AtomicBoolean atomicBoolean = new AtomicBoolean();
int iThreadCount = 3;
final CyclicBarrier cyclicBarrier = new CyclicBarrier(iThreadCount);
final CountDownLatch countDownLatch = new CountDownLatch(1);
final String[] strFinalResult = new String[1];
ExecutorService executorService = Executors.newFixedThreadPool(iThreadCount);
for (int i = 0; i < iThreadCount; i++) {
executorService.submit(new Runnable() {
@SneakyThrows
@Override
public void run() {
// 大家一起执行
cyclicBarrier.await();
// 发现没必要执行了, 就直接中断
boolean bFlag = atomicBoolean.get();
if (bFlag) {
Thread.currentThread().interrupt();
throw new InterruptedException();
}
String strResult = new RemoteInterface().getData();
// 执行完了, 发现不是第一名, 中断掉
bFlag = atomicBoolean.compareAndSet(false, true);
if (bFlag == false) {
Thread.currentThread().interrupt();
throw new InterruptedException();
}
strFinalResult[0] = strResult;
countDownLatch.countDown();
}
});
}
executorService.shutdown();
System.out.println("开始获取...");
countDownLatch.await();
System.out.println("获取执行结果" + strFinalResult[0]);
// for (Future future : listFuture) {
// System.out.println("开始获取...");
// try {
// System.out.println("获取执行结果" + future.get());
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
}
class RemoteInterface {
public String getData() {
String strThreadName = Thread.currentThread().getName();
// 模拟远程调用的耗时
Integer iSleepTime = new Random().nextInt(10000);
System.out.println(String.format("%s: 开始拉取远程数据. %s", strThreadName, iSleepTime));
try {
Thread.sleep(iSleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("%s: 我执行完了", strThreadName));
return strThreadName;
}
}