Java--面包师与消费者2(发送线程与接收线程)

线程协作:采用信号量和同步方法使发送线程与接收线程同步运行
加锁+信号量(isEmpty)+pv操作(notify()和wait())

public class bufferLock {//加互斥锁的缓冲区

    private int value;//共享变量
    private boolean isEmpty=true;
    public synchronized void put(int i){//同步方法
        while(!isEmpty)//生产的面包不为空时,面包师就等
            try {
                this.wait();//是调用该方法当前线程等待状态
            } catch (InterruptedException e) {

            }
        value=i;//当value空,value获得值
        isEmpty=false;//设置value不为空(信号量)
        notify();//唤醒其他等待线程
    }
    public synchronized int get(){
        while(isEmpty)//面包被吃完,就等待
            try {
                this.wait();
            } catch (InterruptedException e) {

            }
        isEmpty=true;
        notify();
        return value;
    }
}
class sender extends Thread{
    private bufferLock buffer;
    public sender(bufferLock buffer) {
        this.buffer=buffer;
    }
    public void run() {
        for(int i=1;i<6;i++){
            buffer.put(i);
            System.out.println("sender put:"+i);
        }
    }
}
class receiver extends Thread{
    private bufferLock buffer;
    public receiver(bufferLock buffer) {
        this.buffer=buffer;
    }
    public void run() {
        for(int i=1;i<6;i++){
            System.out.println("receiver get:"+buffer.get());
        }
    }
    public static void main(String args[]){
        bufferLock buffer=new bufferLock();
        (new sender(buffer)).start();
        (new receiver(buffer)).start();
    }
}

运行结果:
sender put:1
sender put:2
receiver get:1
receiver get:2
sender put:3
receiver get:3
sender put:4
receiver get:4
sender put:5
receiver get:5

你可能感兴趣的:(线程)