关于生产者与消费者之间的问题,其实在你准确理解了线程的概念和方法的用法后,就很容易理解了。
以下是偶写的一个关于生产者与消费者的程序,看看对你理解有没有帮助。
//生产者
class Producer implements Runnable{
private WOWOTou wwt=null;
private Basket bs=null;
private static int id=1;
private static boolean state=true;
Producer(Basket bs){
this.bs=bs;
}
public WOWOTou produce(){
try {
Thread.sleep( (long) (Math.random()*8000));
} catch (InterruptedException e) {
e.printStackTrace();
}
wwt=new WOWOTou(id);
//输出调试语句
System.out.println();
System.out.println(Thread.currentThread().getName()+"生产了id为"+id+"的包子");
id++;
return wwt;
}
public void push(){
bs.push(wwt);
wwt=null;
}
public void run() {
while(state){
synchronized(this){
produce();
push();
}
}
}
}
//消费者
class Custmer implements Runnable{
private Basket bs=null;
private WOWOTou wwt=null;
private static boolean state=true;
public Custmer(Basket bs) {
this.bs = bs;
}
public void cousme(){
try{
Thread.sleep((long) (Math.random()*8000));
}catch(InterruptedException e){
e.printStackTrace();
}
// 输出调试语句
System.out.println();
System.out.println(Thread.currentThread().getName()+"消费id为"+wwt.getWOWOTouID()+"的包子");
wwt=null;
}
public void pop(){
wwt=bs.pop();
}
public void run() {
while(state){
synchronized(this){
pop();
cousme();
}
}
}
}
//装WOWOTou的Basket
class Basket{
private int index=0;
private final static int max=5;
private WOWOTou wwt=null;
private WOWOTou[] wwtbs=new WOWOTou[5];
private Producer p=null;
private static Basket bs=null;
private Basket(){}
public synchronized static Basket getBasket(){
if(bs==null)
bs=new Basket();
return bs;
}
public synchronized void push(WOWOTou wwt){
while(index==max){
System.out.println("包子满了,赶紧吃包子");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
//输出调试语句
System.out.println();
System.out.println("这是"+Thread.currentThread().getName()+"生产的id为"+wwt.getWOWOTouID()+"的包子");
wwtbs[index++]=wwt;
}
public synchronized WOWOTou pop(){
while(index==0){
System.out.println();
System.out.println("没包子了,赶紧生产包子");
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
if(index>0)
index--;
//输出调试语句
System.out.println();
System.out.println(Thread.currentThread().getName()+"拿到id为"+wwtbs[index].getWOWOTouID()+"的包子");
return wwtbs[index];
}
}
class WOWOTou{
private int id=0;
WOWOTou(int id){
this.id=id;
}
public int getWOWOTouID(){
return id;
}
}
当你明白线程后,就应该考虑多线程和线程的性能问题,尽量减小锁的粒度,但要注意死锁问题。