并发编程 常用工具Future CountDownLatch的使用例子备忘录
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
public class ConcurrentTest {
public static void main(String args[]) {
System.out.println("hello word.");
final int size = 10;
CountDownLatch countlatch=new CountDownLatch(size);
Map<String, Long> concurrentHashMap = new ConcurrentHashMap<>();
List<Future<Long>> list = new ArrayList<>();
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i<size; i++) {
Future<Long> ret = executorService.submit(new Task(countlatch, concurrentHashMap));
//Future.get Waits if necessary for the computation to complete, and then
// * retrieves its result. 故此处不应该使用这种方式,
// 他是在这等了,正确的用法时,把这些都放入list,等到都ready了再去read
// System.out.println( "future " + ret.get()); // 阻塞的
list.add(ret);
}
try {
countlatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i=0; i<size; i++) {
try {
System.out.println("future get" + list.get(i).get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
int index = 0;
for (Map.Entry<String, Long> entry: concurrentHashMap.entrySet()
) {
System.out.println("index : " + index ++ + " entry key " + entry.getKey() + ", value " + entry.getValue());
}
}
}
class Task implements Callable<Long> {
CountDownLatch countDownLatch;
Map<String,Long> rets;
public Task(CountDownLatch countDownLatch, Map<String,Long> rets) {
this.countDownLatch = countDownLatch;
this.rets = rets;
}
@Override
public Long call() {
Long id = Thread.currentThread().getId();
System.out.println("thread id " + id);
// 这样用其实不太标准,毕竟这个时候有可能已经 count down,但还没有返回
this.rets.put(id + "", id);
this.countDownLatch.countDown();
return new Long(id);
}
}