package service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
interface Service<V> {
}
interface ServiceProvider<V extends Product> extends Service<V> {
V get();
void set(V v);
}
interface Product {
}
class Tmall implements ServiceProvider {
private List<Product> storage;
private int MAX_COUNT;
private int count;
private Tmall(int maxCount) {
storage = Collections.synchronizedList(new ArrayList<>(maxCount));
MAX_COUNT = maxCount;
}
// 消费者线程消费的方法
@Override
public synchronized Product get() {
while (count <= 0) {
try {
System.out.println("库存没了,消费者等待");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Product product = storage.remove(--count);
System.out.println(Thread.currentThread().getName() + "消费者消费,当前库存为:" + count);
notifyAll(); //通知生产者线程生产
return product;
}
// 生产者线程生产的方法
@Override
public synchronized void set(Product product) {
while (count >= MAX_COUNT) {
try {
System.out.println("库存满了,生产者等待");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.add(product);
count++;
System.out.println(Thread.currentThread().getName() + "生产者生产,当前库存为:" + count);
notifyAll(); // 通知消费者线程消费
}
public static class Producer implements Runnable {
private Tmall tmall;
Producer(Tmall tmall) {
this.tmall = tmall;
}
@Override
public void run() {
while (true) {
tmall.set(new Item());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static class Consumer implements Runnable {
private Tmall tmall;
Consumer(Tmall tmall) {
this.tmall = tmall;
}
@Override
public void run() {
while (true) {
Product product = tmall.get();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private static class Item implements Product {}
public static void main(String[] args) {
Tmall tmall = new Tmall(10);
Producer p = new Producer(tmall);
Consumer c = new Consumer(tmall);
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
}
}
生产和消费
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- RabbitTemplate类是简化RabbitMQ访问的工具类(发送和接收消息) 总结:1.使用RabbitTe...
- 网上有太多此类帖子,然而本帖比他们全面。 背景 有一台阿里云服务器A,用作测试服务器,一台华为服务器B,用作生产服...
- 今天凌晨,NEXT Web 2.0悄然上线了。 这是 NEXT 上线一周年来首次较大规模的改版。一年来,我们一直在...