//生产者消费者问题通常用于解决多线程环境下的数据共享和同步问题。阻塞队列是一个很好的解决方案,//其中LinkedBlockingQueue是一个线程安全的队列实现。
import java.util.concurrent.LinkedBlockingQueue;
class Producer implements Runnable {
private LinkedBlockingQueue<Integer> queue;
public Producer(LinkedBlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("Produced: " + i);
queue.put(i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
private LinkedBlockingQueue<Integer> queue;
public Consumer(LinkedBlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
Integer value = queue.take();
System.out.println("Consumed: " + value);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ProducerConsumerExample {
public static void main(String[] args) {
LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
Thread producerThread = new Thread(new Producer(queue));
Thread consumerThread = new Thread(new Consumer(queue));
producerThread.start();
consumerThread.start();
}
}
多线程——使用阻塞列队LinkedBlockingQueue<E>实现生产者消费者程序。
最新推荐文章于 2024-09-18 09:30:48 发布