import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class TestFuture {
public static void main(String[] args) {
TestFuture testFuture = new TestFuture();
int taskCount = 3;
List<Future<String>> futures = new ArrayList<>(taskCount);
CountDownLatch downLatch = new CountDownLatch(taskCount);
ExecutorService executorService = new ThreadPoolExecutor
(taskCount, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
for (int i = 0; i < taskCount; i++) {
Future<String> future = executorService.submit(testFuture.executeTask(i, downLatch));
futures.add(future);
}
System.out.println("do other things");
try {
downLatch.await();
executorService.shutdown();
List<String> result = testFuture.getFutureResult(futures);
for (String s : result) {
System.out.println(s);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Callable<String> executeTask(int i, CountDownLatch downLatch) {
return () -> {
Thread.sleep(i * 1000L);
downLatch.countDown();
return "Result " + Thread.currentThread().getName();
};
}
public List<String> getFutureResult(List<Future<String>> futures) {
List<String> result = new ArrayList<>(3);
for (Future<String> future : futures) {
if (future.isDone() && !future.isCancelled()) {
try {
result.add(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
return result;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)