Java 多线程:生产者-消费者模式实现及信号量应用
本示例使用 Java 多线程和信号量实现经典的生产者-消费者模式。
程序代码如下:
package op1;
import java.util.concurrent.Semaphore; //semaphore
public class ProduceAndConsume {
private static Integer count = 0;
// Create three semaphores
final Semaphore notFull = new Semaphore(10); //new Semaphore(10)The initial value representing the semaphore not full is 10
final Semaphore notEmpty = new Semaphore(0);
final Semaphore mutex = new Semaphore(1);
public static void main(String[] args) {
ProduceAndConsume pc = new ProduceAndConsume();
new Thread(pc.new Producer()).start(); //Start 5 producer threads and 5 consumer threads to simulate concurrent execution by both producers and consumers
new Thread(pc.new Consumer()).start();
new Thread(pc.new Producer()).start();
new Thread(pc.new Consumer()).start();
new Thread(pc.new Producer()).start();
new Thread(pc.new Consumer()).start();
new Thread(pc.new Producer()).start();
new Thread(pc.new Consumer()).start();
}
class Producer implements Runnable {
@Override
public void run() {
try {
notFull.acquire(); //Apply for an empty buffer
mutex.acquire(); //Request buffer pool
count++;
System.out.println(Thread.currentThread().getName() + 'Producer production,Currently, there are a total of' + count);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mutex.release();
notEmpty.release();
}
}
}
class Consumer implements Runnable {
@Override
public void run() {
try {
notEmpty.acquire();
mutex.acquire();
count--;
System.out.println(Thread.currentThread().getName() + 'consumer spending,Currently, there are a total of' + count);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mutex.release();
notFull.release();
}
}
}
}
分析:
- 初始缓冲区状态: 初始化时,
notFull信号量值为 10,notEmpty信号量值为 0。这意味着初始有 10 个空缓冲区,0 个满缓冲区。 - 信号量
mutex的互斥访问:mutex信号量用于实现对缓冲池的互斥访问,即同一时间只允许一个生产者或消费者访问缓冲池。
代码解释:
-
生产者
Producer类:notFull.acquire():申请一个空缓冲区。如果当前没有空缓冲区,线程会阻塞等待。mutex.acquire():申请对缓冲池的访问权限。如果其他线程正在访问缓冲池,线程会阻塞等待。count++:生产一个产品,并将计数器count加 1。mutex.release():释放对缓冲池的访问权限。notEmpty.release():释放一个满缓冲区。
-
消费者
Consumer类:notEmpty.acquire():申请一个满缓冲区。如果当前没有满缓冲区,线程会阻塞等待。mutex.acquire():申请对缓冲池的访问权限。如果其他线程正在访问缓冲池,线程会阻塞等待。count--:消费一个产品,并将计数器count减 1。mutex.release():释放对缓冲池的访问权限。notFull.release():释放一个空缓冲区。
总结:
本示例展示了使用 Java 多线程和信号量实现生产者-消费者模式,以及信号量在控制并发访问和资源同步中的重要作用。mutex 信号量确保了对共享资源的互斥访问,notFull 和 notEmpty 信号量则协调了生产者和消费者的工作,以确保生产者不会在缓冲区满时生产,消费者不会在缓冲区空时消费。
原文地址: https://www.cveoy.top/t/topic/nTGS 著作权归作者所有。请勿转载和采集!