首页 > 代码库 > 线程之间的通信(卖面包)

线程之间的通信(卖面包)

package mianbao;

import java.util.Random;

public class TestBread {

    /**
     * @param args
     */
    public static void main(String[] args) {
    Store store=new Store();
    Maker m=new Maker(store);
    Saler s=new Saler(store);
    m.start();
    s.start();

    }

}
//面包店类
class Store{
    int num=0;//面包的个数
    Random r=new Random();
//生产面包    
public synchronized    void make(){
    if(num==0){
        num=r.nextInt(20)+1;
        System.out.println("面包生产完毕         共有"+num);
    }
//通知消费者来卖面包,自己阻塞    
    this.notify();
    try {
        this.wait();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
}
//销售面包
public synchronized void sale(){
    if(num>0){
        int i=r.nextInt(num)+1;
        System.out.println("销售面包数:"+i);
        num-=i;
    }else{
        //通知生产者生产面包
        this.notifyAll();//在这个程序里与notify()相同
        try {
            this.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
    
}
//生产者线程
class Maker extends Thread{
    Store s;

    public Maker(Store s) {
        super();
        this.s = s;
    }
    public void run(){
        while(true){
            s.make();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
class Saler extends Thread{
    Store s;

    public Saler(Store s) {
        super();
        this.s = s;
    }
    public void run(){
        while(true){
            s.sale();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 

线程之间的通信(卖面包)