该代码使用 Java 中的 Semaphore 来实现经典的生产者消费者模式。

Semaphore 的使用

Semaphore 是一种同步工具,用于控制对共享资源的访问。它维护着一组许可证,每个线程在访问资源之前必须获得许可证。acquire() 方法用于申请许可证,release() 方法用于释放许可证。

代码示例

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

资源申请和释放

  • **申请资源:**acquire() 方法用于申请资源。在 Producer 类中,notFull.acquire()mutex.acquire() 是申请资源的方法。在 Consumer 类中,notEmpty.acquire()mutex.acquire() 是申请资源的方法。

  • **释放资源:**release() 方法用于释放资源。在 Producer 类中,mutex.release()notEmpty.release() 是释放资源的方法。在 Consumer 类中,mutex.release()notFull.release() 是释放资源的方法。

总结

Semaphore 是一个强大的同步工具,可以用于实现生产者消费者模式和其他需要控制对共享资源访问的场景。acquire() 和 release() 方法是 Semaphore 的核心方法,分别用于申请和释放资源。通过合理使用 Semaphore,可以有效地管理多线程之间的同步问题。

Java 多线程生产者消费者模式:Semaphore 实现

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

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