生产者-消费者(java并发)

首先是Productor.java
package org.iteye.bbjava.currency.pc;


public class Productor implements Runnable {

CQueue<String> queue;
int i = 0;

public Productor(CQueue<String> queue) {
this.queue = queue;
}

@Override
public void run() {
while (!Thread.interrupted()) {
if (queue.size() > 200) {
System.out.println("仓库满了,productor 休息一下");
} else {

try {
System.out.println(".");
Thread.sleep(500);
queue.add(""+i++);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
}


}


接下来是仓库 CQueue.java
package org.iteye.bbjava.currency.pc;

import java.util.LinkedList;
import java.util.Queue;

public class CQueue<T> {

public Queue<T> queue = new LinkedList<T>(); ;

public CQueue(){

}

public synchronized T poll() { //consumer 从仓库取出产品
if(queue.size() <= 0 ){
try {
System.out.println("仓库空了,里面没东西,consumer 休息一下 size:"+queue.size());
wait(1200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
notify();
}
return queue.poll();
}

public synchronized void add(T elem){
if(queue.size() >= 200){
try {
System.out.println("仓库满了,容不下更多东西了,productor 休息一下 size:"+queue.size());
wait(1200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}else{
queue.add(elem);
notify();
}
}

public int size(){
return queue.size();
}

}


再者是Consumer.java
package org.iteye.bbjava.currency.pc;

import java.util.Queue;

public class Consumer implements Runnable {

CQueue<String> queue;


@Override
public void run() {
while (!Thread.interrupted()) {
if (queue.size() < 0) {
System.out.println("仓库空了,consumer 休息");

} else {
try {
Thread.sleep(500);
System.out.println(this.consume());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

}

public Consumer(CQueue<String> queue) {
this.queue = queue ;
}

public String consume(){
return this.queue.poll();
}
}


客户端 TestProductorAndConsumer .java

package org.iteye.bbjava.currency.pc;

public class TestProductorAndConsumer {

public static void main(String []args){

CQueue<String> cq = new CQueue<String>();
System.out.println(cq.size());
Thread t2 = new Thread(new Productor(cq));
Thread t3 = new Thread(new Productor(cq));
Thread t1 = new Thread(new Consumer(cq));
Thread t4 = new Thread(new Consumer(cq));

t4.start();
t3.start();
t2.start();
t1.start();


}
}


生产者与消费者,纯回顾一下,手写的,主要是加深印象。

待整理……
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值