import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class Test{
private int size = 10;
/**
* 空位的信号量 初始全空
*/
private Semaphore empty = new Semaphore(size);
/**
* 有的信号量 初始什么都没有
*/
private Semaphore full = new Semaphore(0);
/**
* 承载的容器
*/
private Integer[] content = new Integer[size];
/**
* 下一个可以存储元素的位置
*/
private int addIndex = 0;
/**
* 下一个可以读取元素的位置
*/
private int readerIndex = 0;
/**
* 增加元素
* @param i
* @throws InterruptedException
*/
public void add(Integer i) throws InterruptedException {
//P 增加元素,当然需要看看是否有空位了。
empty.acquire();
//拿取到了空位 准备访问临界资源存储数据了
synchronized (content) {
//临界区资源
content[addIndex] = i;
addIndex = (addIndex+1)%size;
}
//V 已经放入一个元素 通知full有一个元素了
full.release();
}
/**
* 消费元素
* @return
* @throws InterruptedException
*/
public Integer pop() throws InterruptedException {
//P 消费元素 当然需要看看是否有元素了
full.acquire();
//成功分配到一个元素的消费权限 开始从临界资源拿取元素
Integer result = null;
synchronized (content) {
//临界区资源
result = content[readerIndex] ;
readerIndex = (readerIndex+1)%size;
}
//V 已经取出一个元素 告知empty有一个空位了
empty.release();
return result;
}
public static void main(String[] args) {
final Ab s = new Ab();
ExecutorService a = Executors.newCachedThreadPool();
ExecutorService b = Executors.newCachedThreadPool();
final Random r = new Random();
for (int i = 0; i < 100; i++) {
final int k = i;
a.submit(()->{
try {
s.add(k);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
for (int i = 0; i < 101; i++) {
b.submit(()->{
try {
//Thread.sleep(r.nextInt(10000));
System.out.println(s.pop());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
a.shutdown();
b.shutdown();
}
}
基于java信号量Semaphore实现生产者消费者逻辑
于 2025-10-10 14:11:03 首次发布

1124

被折叠的 条评论
为什么被折叠?



