本文将详细介绍Java多线程编程中的经典模式——生产者-消费者模式,并使用Semaphore信号量来实现线程间的同步与互斥。

1. 代码示例

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();
			}
		}
	}
}

2. 代码解析

  • 生产者-消费者模式:生产者线程负责生产产品,并将产品放入缓冲池中;消费者线程负责从缓冲池中获取产品,并进行消费。

  • Semaphore信号量:Semaphore是一个计数信号量,用于控制对共享资源的访问。

    • notFull: 代表缓冲池中剩余空间数量,初始值为10,表示缓冲池中有10个空闲空间。生产者线程在生产产品前需要获取notFull信号量,如果信号量为0,则表示缓冲池已满,生产者线程需要等待。
    • notEmpty: 代表缓冲池中产品数量,初始值为0,表示缓冲池中没有产品。消费者线程在消费产品前需要获取notEmpty信号量,如果信号量为0,则表示缓冲池为空,消费者线程需要等待。
    • mutex: 互斥信号量,初始值为1,用于保证对缓冲池的访问是互斥的。

3. count变量的含义

count变量表示当前缓冲池中的产品数量。在生产者线程生产产品时,count会增加;在消费者线程消费产品时,count会减少。

4. 总结

本文介绍了Java多线程编程中的生产者-消费者模式,并使用Semaphore信号量来实现线程间的同步与互斥。通过分析代码示例,详细讲解了Semaphore的使用方法以及count变量在程序中的含义。生产者-消费者模式是多线程编程中非常常用的模式,它能够有效地协调生产者和消费者之间的工作,提高程序的效率。

Java多线程编程:生产者-消费者模式详解(Semaphore实现)

原文地址: https://www.cveoy.top/t/topic/nTFY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录