一直被忽略的java 多线程并发工具类 CountDownLatch、Semaphore

CountDownLatch: 进行等待,知道发生指定数量事件后停止

构造方法:CountDownLatch(int num)
num是指锁存器而必须发生的事件次数。
主要方法:
await() : 当计数器(也就是上面的num)等于0时才结束等待
countDown(): 计数器(num)递减


Semaphore: 实现经典信号量

构造方法:Semaphore(int num)
num是产生的信号量个数
主要方法:
acquire(): 获取一个信号量
release(): 释放一个信号量


代码如下:

package com.test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class Question2 implements Runnable{
    private String name;
    private Semaphore sem;
    private CountDownLatch downLatch;

    public Question2(String name, Semaphore sem,CountDownLatch downLatch) {
        super();
        this.name = name;
        this.sem = sem;
        this.downLatch = downLatch;
    }

    public void test(String name){
        System.out.println(name + " in!");
        try {
            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + " out!");
    }

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        int thread_num = 10;
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore sem = new Semaphore(1); //每次产生信号量个数
        CountDownLatch downLatch = new CountDownLatch(5); //初始化同步器

        for(int i=0; i< thread_num;i++){
            executorService.execute(new Question2("test "+i, sem,downLatch));
        }
        downLatch.await();
        executorService.shutdown();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            sem.acquire();
            this.test(this.name);
            sem.release();
            downLatch.countDown();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值