以下是使用Java编写的一个简单的生产者-消费者模式的示例,这里采用阻塞队列来实现线程间的
通信与同步:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;public class ProducerConsumerExample {// 定义一个阻塞队列作为缓冲区private static BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);public static void main(String[] args) {// 启动生产者线程Thread producerThread = new Thread(new Producer());producerThread.start();// 启动消费者线程Thread consumerThread = new Thread(new Consumer());consumerThread.start();}// 生产者类static class Producer implements Runnable {@Overridepublic void run() {try {for (in