java 并发编程 future CountDownLatch

 
 

并发编程  常用工具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);
    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值