目标使用Semaphore构建简单的生产者消费者模型
Semaphore
- 基于AQS实现的,用于控制临界区的线程并行数量。
- acquire(int val),不填值时,默认消耗一个信号,填值时根据值消耗信号。
- release(int val),不填值时,默认增加一个信号,填值时根据值增加信号。release的值可以比线程进来时设定的acquire中的信号值要大。
代码:
思路:
- 运用两个Semaphore,分别是消费者Semaphore与生产者Semaphore进行互相消耗与增加,控制queue中的size恒定在一个范围内。
- 由于生产者的临界区是多线程同时执行的,因此生产队列要使用线程安全的ConcurrentLinkedQueue
package com.miracle.study.concurrent;
import com.miracle.study.syn.ProducerCustomerTest;
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author Miracle
* @date 2021/4/14 13:22
*/
public class SemaphoreTest {
private static final Random RANDOM = new Random();
private ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue();
/**
* 消费者信号
*/
private Semaphore consumerSem = new Semaphore(0);
/**
* 生产者信号
*/
private Semaphore producerSem = new Semaphore(10);
/**
* 模拟业务函数
*
* @return
* @throws InterruptedException
*/
public int doSomething() throws InterruptedException {
var data = RANDOM.nextInt(100);
Thread.sleep(1000);
return data;
}
/**
* 生产者
*
* @throws InterruptedException
*/
public void producer() throws InterruptedException {
// 生产者消耗一个信号
producerSem.acquire();
// 生产业务
queue.add(doSomething());
// 消费者增加一个信号
consumerSem.release();
}
public void comsumer() throws InterruptedException {
// 消费者消耗一个信号
consumerSem.acquire();
// 消费者处理业务
queue.remove();
System.out.println(queue.size());
// 生产者增加一个信号
producerSem.release();
}
public static void main(String[] args) throws InterruptedException {
var pc = new SemaphoreTest();
for (int i = 0; i < 10; i++) {
new Thread(() -> {
while (true) {
try {
pc.producer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
new Thread(() -> {
try {
while (true){
pc.comsumer();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}