生产者和消费者问题

感觉还有点小问题 , 大家帮忙看看



import java.util.ArrayList;

public class Generant_Customer {
public static void main(String[] args) {
Collection c = new Collection();
Generant gen = new Generant(c);
Customer cus = new Customer(c);

new Thread(gen,"gen01").start();
new Thread(gen,"gen02").start();
new Thread(gen,"gen03").start();
new Thread(cus,"cus01").start();
new Thread(cus,"cus02").start();
}
}
/**
* 资源类 , 消费者和生产者共同操作的资源
*/
class Collection {
ArrayList<String> collection = new ArrayList<String>();
static final int length = 10;
int index = 1 ;
int operateCount = 0;

/* 生产者生产 */
public synchronized void add(){
if(collection.size()>=length){
try {
wait();
} catch (InterruptedException e) {
System.out.println("add() has been interrupted !");
System.exit(1);
}
}
notifyAll();//唤醒在此对象监视器上等待的单个线程
collection.add("馒头 编号:"+index);
System.out.println("生产者" +Thread.currentThread().getName() + collection.get(index-1));
index ++ ;
operateCount++;
}

/* 消费者消费 */
public synchronized void pop(){
if(collection.size() == 0){
try {
wait();
} catch (InterruptedException e) {
System.out.println("pop() has been interrupted !");
System.exit(1);
}
}
notifyAll(); //唤醒在此对象监视器上等待的单个线程
System.out.println("--消费者" +Thread.currentThread().getName() + collection.get(collection.size()-1));
collection.remove(collection.size()-1);
index -- ;
operateCount++;
}
}

class Generant implements Runnable{
Collection coll = null ;

public Generant(Collection collection ){
this.coll = collection ;
}

/* 生产者开始执行 */
public void run() {
while(true){
coll.add();
System.out.println(coll.operateCount);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Generant.run() has been interrupted !\\n" +
" System continue...");
}
}
}
}

class Customer implements Runnable{
Collection coll = null ;
/* 线程开关 */
boolean doRun = true ;

public Customer(Collection collection ){
this.coll = collection ;
}
/* 消费者开始执行 */
public void run() {
while(doRun){
coll.pop();
System.out.println(coll.operateCount);
try {
Thread.sleep(150);
} catch (InterruptedException e) {
System.out.println("Customer.run() has been interrupted !\\n" +
" System continue...");
}
if(coll.operateCount == 50){
doRun = false;
}
}
}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值