生产者消费者是常见的同步问题。一个队列,头部生产数据,尾部消费数据,队列的长度为固定值。当生产的速度大于消费的速度时,队列逐渐会填满,这时就会阻塞住。当尾部消费了数据之后,生产者就可以继续生产了。
生产者
package com.example; import java.util.List; public class Producer { private List<String> list; public Producer(List<String> list){ this.list = list; } public void produce(String str){ synchronized (list){ if(list.size() >= ProducerConsumer.LIST_SIZE){ try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(0, str); System.out.println("produce item:"+str); } } }
消费者
package com.example; import java.util.List; public class Producer { private List<String> list; public Producer(List<String> list){ this.list = list; } public void produce(String str){ synchronized (list){ if(list.size() >= ProducerConsumer.LIST_SIZE){ try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(0, str); System.out.println("produce item:"+str); } } }
测试类
package com.example; import java.util.ArrayList; import java.util.List; public class ProducerConsumer { public static int LIST_SIZE = 3; public static void main(String[] args){ producerConsumerTest(); } private static void producerConsumerTest(){ List<String> list = new ArrayList<String>(); final Producer producer = new Producer(list); final Consumer consumer = new Consumer(list); new Thread(new Runnable() { @Override public void run() { int count = 0; while(true){ count++; producer.produce("num"+count); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { while(true){ int count = 0; while(true){ consumer.consume(); try { Thread.sleep(2500); } catch (InterruptedException e) { e.printStackTrace(); } } } } }).start(); } }
运行结果:
数据超过3个时候就不能生产了,需要等待消费者。
时间: 2024-12-10 10:25:03