Java

Java16-5 多线程等待唤醒机制

2018-11-11  本文已影响0人  第二套广播体操

多线程间的通信

多个线程处理同一个资源,但是处理的任务却不同
生产者 消费者实例
通过同步,解决没生产就消费的问题
但是出现了连续的生产没有消费的情况,和需求一个,消费一个的情况不符
使用等待唤醒机制
wait();
notify();
notifyAll();


//描述资源
class Bread{
    private String name;
    private int count=0;
    private boolean flog;//默认为false
    public Bread(String name) {
        this.name = name;
    }
    //生产方法
    public synchronized void produce(){
        if(flog) {//如果为true有面包储存 则会进入wait等待因为默认为false则结果为
            //false所以进入else
            try {
            wait();
            }
        catch (InterruptedException e){}
        }
        else {//生产面包
            count++;
        System.out.println(Thread.currentThread().getName()+"生产"+name+"数量"+count);
        flog=true;//将面包改为有存货
        notify();//激活窗口2线程
        }
    }
    //销售方法
    public synchronized void sale(){
        if (!flog){//如果没有储存的面包则结果为true进入wait等待

            try {
                wait();
            }catch (InterruptedException e){}
        }
        else//如果为else则会售出这个面包
        {
            System.out.println(Thread.currentThread().getName()+"销售"+name+"数量"+count);

        flog=false;//将库存改为没有
        notify();//激活窗口1线程
        }
    }
}
//生产窗口
class Producer implements Runnable{
    private Bread bread;
//从外界引入同一对象
    public Producer(Bread bread) {
        this.bread = bread;
    }

    @Override
    public void run() {
            for (int i = 0; i < 20; i++) {
                bread.produce();
            }
    }
}
//销售窗口
class ConSumer implements Runnable{
    private Bread bread;
//从外界引入同一对象
    public ConSumer(Bread bread) {
        this.bread = bread;
    }

    @Override
    public void run() {
            for (int j = 0; j < 20; j++) {
                bread.sale();
            }
    }
}

public class Producer_ConSumerDemo {
    public static void main(String[] args) {
          Bread bread=new Bread("面包");
          Producer producer=new Producer(bread);
          ConSumer conSumer=new ConSumer(bread);
          Thread t1=new Thread(producer,"窗口1");
          Thread t2=new Thread(conSumer,"窗口2");
          t1.start();
          t2.start();
    }
}
上一篇下一篇

猜你喜欢

热点阅读