java实现生产消费者问题,Java实现生产者,消费者问题

高手给布置的任务。

多线程最开始学Java的时候学的,今天写得很顺,自己都觉得挺吃惊。

还得查查资料,看这么写是不是最优的。

package com.weishubin.thread;

//生产者

public class Producer implements Runnable {

private ProductionStore store;

public Producer(ProductionStore store) {

this.store = store;

}

@Override

public void run() {

int i = (int) (100 * Math.random());

Production p = new Production(i);

try {

this.store.produce(p);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

package com.weishubin.thread;

public class Consumer implements Runnable {

private ProductionStore store;

public Consumer(ProductionStore store) {

this.store = store;

}

@Override

public void run() {

try {

Production p = this.store.consume();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

package com.weishubin.thread;

//产品

public class Production {

private int id;

public Production(int id) {

this.id = id;

}

public String toString() {

return "production:" + id;

}

}

package com.weishubin.thread;

import java.util.LinkedList;

public class ProductionStore {

private LinkedList productions = new LinkedList();

private int MAX_COUNT = 10;//最多存放10个产品

private int MIN_COUNT = 0;

public void produce(Production p) throws InterruptedException {

synchronized (productions) {

while (productions.size() == MAX_COUNT) {

System.out.println(Thread.currentThread() + " 生产等待:" + p);

productions.wait();

}

System.out.println(Thread.currentThread() + " 生产:" + p);

productions.add(p);

if (productions.size() == 1) {

productions.notifyAll();

}

}

}

public Production consume() throws InterruptedException {

synchronized (productions) {

int size = productions.size();

while (productions.size() == MIN_COUNT) {

System.out.println(Thread.currentThread() + "消费等待");

productions.wait();

}

Production p = productions.pop();

System.out.println(Thread.currentThread() + " 消费产品:" + p);

if (size == MAX_COUNT) {

productions.notifyAll();

}

return p;

}

}

}

package com.weishubin.thread;

public class App {

public static void main(String[] args) {

ProductionStore store = new ProductionStore();

for (int i = 0; i < 20; i++) {

Thread t = new Thread(new Producer(store));

t.start();

}

for (int i = 0; i < 20; i++) {

Thread t = new Thread(new Consumer(store));

t.start();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值