您的位置:首页 > 编程语言 > Java开发

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

2017-09-27 14:28 645 查看
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();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息