Java并发编程 CountDownLatch和Semaphore

CountDownLatch是JDK1.5之后提供的同步组件,它的功能是完成同步阻塞功能,也就是让一个线程或多个线程进行等待,直到其他线程完成,它用计数器来进行初始化,它是原子操作的。调用await方法的线程会等待,而其他线程执行完之后才会调用countDown()方法对计数器进行-1操作。当计数器成为0之后,调用await方法的程序才会继续执行。CountDownLatch一般与Semaphore共用,Semaphore可以控制同时启动的线程数,它是通过锁来控制线程的起停操作的

典型应用:
主线程

    CountDownLatch cdl = new CountDownLatch(lstCabinet.size());  //初始化计数器
    HashMap cabMap = new HashMap();
    HashMap cabinetMap = new HashMap();
    HashMap cabinetUserMap = new HashMap();
    for (Cabinet cabinet:lstCabinet){

        CabPowerOnCheckThread cabPowerOnCheckThread = new CabPowerOnCheckThread();
        cabPowerOnCheckThread.setCdl(cdl);
        cabPowerOnCheckThread.setCabinetDao(cabinetDao);
        cabPowerOnCheckThread.setCabinetUserDao(cabinetUserDao);
        cabPowerOnCheckThread.setCabinet(cabinet);
        cabPowerOnCheckThread.setCabMap(cabMap);
        cabPowerOnCheckThread.setCabinetMap(cabinetMap);
        cabPowerOnCheckThread.setCabinetUserMap(cabinetUserMap);
        Thread thread = new Thread(cabPowerOnCheckThread);
        thread.setUncaughtExceptionHandler(new MyUncaughtExceptionhandler());
        thread.start();

    }
    //  在这里等待  超时的情况下抛出异常  
    boolean asd = cdl.await(3, TimeUnit.MINUTES);

开启的子线程

public void run() {
    try {
        semaphore.acquire();// 加锁,当锁的数量等于Semaphore的设定值时则拒绝其他线程的请求
        WorkOrderInfoServiceImpl workOrderInfoServiceImpl = new WorkOrderInfoServiceImpl();
        HashMap resultMap = workOrderInfoServiceImpl
                .cabNumCheck(cabinet,  cabinetDao);
        if (resultMap.containsKey("err")){
            cabMap.put("err", resultMap.get("err").toString());
        }
        else {
            Map map = resultMap;
            if (map.size() == 0){
                cabMap.put("err", "数据检索失败");
            }
            
            for (Entry entry : map.entrySet()) {
                
                if (cabinetMap.containsKey(entry.getKey())){
                    cabMap.put("err", "xxxxx"+entry.getKey());
                }
                else {
                    cabinetMap.put(entry.getKey(), entry.getValue());
                }
                Cabinet cabinet = new Cabinet();
                cabinet = (Cabinet) entry.getValue();
                if (cabinet != null){
                    CabinetUser cabinetUser = new CabinetUser();
                    cabinetUser = workOrderInfoServiceImpl.cabUserCheck(cabinet.getId(), cabinetUserDao);
                    if (cabinetUser != null){
                        cabinetUserMap.put(cabinet.getId(),cabinetUser);
                    }
                }
            }

        }
        cdl.countDown();  //每次执行完之后执行-1操作,这里是原子操作
        semaphore.release();// 释放一把锁,
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {

    }

你可能感兴趣的:(Java并发编程 CountDownLatch和Semaphore)