Thread多线程4-线程通信

线程通信

生产者消费者模式

  • 假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中的产品取走消费;
  • 如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到消费者取走仓库中的产品;
  • 如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品;
  • 仓库相当于数据缓存区

这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件:

  • 对于生产者,没有生产产品前,要通知消费者等待,而生产了产品后,又要马上通知消费者消费;
  • 对于消费者,在消费之后,要通知生产者生产新的产品以供消费;

在生产者消费者问题中,仅有synchronized是不够的:

  • synchronized 可以阻止并发更新同一个共享资源,实现了同步;
  • synchronized 不能用来实现不同线程之间的消息传递(通信);

java提供了几个方法解决线程之间的通信问题:
wait() //表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁;
wait(long timeout) //指定等待的毫秒数;
notify() //唤醒处于等待状态的线程;
notifyAll() //唤醒同一个对象上所有调用wait()方法的线程,优先级高的线程优先调度;
【注意】以上方法均是Object类的方法,都只能在同步方法或同步代码块中使用,否则会抛出异常ILLegalMonitorStateException

解决方式1-管程法
生产者:负责生产数据的模块(可能是方法、对象、线程、进程);
消费者:负责处理数据的模块(可能是方法、对象、线程、进程);
缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓冲区”;
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿数据;

/**
 * 生产者消费者模型-->利用缓冲区:管程法
 */
public class PandC {
    public static void main(String[] args) {
        SynContainer container=new SynContainer();
        new Producer(container).start();
        new Consumer(container).start();
    }
}
//生产者
class Producer extends Thread{
    SynContainer container;
    public Producer(SynContainer container){
        this.container=container;
    }
    //生产
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("生产了:"+i+"号产品");
            container.put(new Product(i));
        }
    }
}
//消费者
class Consumer extends Thread{
    SynContainer container;
    public Consumer(SynContainer container){
        this.container=container;
    }
    //消费
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("消费了-->"+container.get().id+"号产品");
        }
    }
}
//产品
class Product{
    int id;
    public Product(int id){
        this.id=id;
    }
}
//缓冲区,容器
class SynContainer{
    //容器大小
    Product[] products = new Product[10];
    //产品数量
    int count=0;
    //生产者放入产品
    public synchronized void put(Product product){
        //如果容器满了
        if(count==products.length){
            //通知消费者消费,生产等待
            try{
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        //如果没满,需要放入产品
        products[count]=product;
        count++;
        //可以通知消费者消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Product get(){
        //判断能否消费
        if (count==0){
            //等待生产者生产
            try{
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Product product = products[count];
        //吃完了,通知生产者生产
        this.notifyAll();
        return product;
        }
}

**解决方式2-信号灯法

/**
 * 消费者生产者模型->利用标志位:信号灯法
 */
public class PCSignal {
    public static void main(String[] args) {
        TV tv=new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}
//生产者:演员
class Player extends Thread{
    TV tv;
    public Player(TV tv) {
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i/5==0){
                this.tv.play("插播广告");
            }else{
                this.tv.play("西游记");
            }
        }
    }
}

//消费者:观众
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv) {
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}
//产品:节目
class TV{
    String show; //表演的节目
    boolean flag=true; //拍戏
    //演员拍戏,观众等待
    public synchronized void play(String show){
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("*排了戏:"+show);
        //通知观众观看
        this.notifyAll();
        this.show=show;
        this.flag=!this.flag;
    }
    //观众观看,演员等待
    public synchronized void watch(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("-看了戏:"+show);
        //通知演员拍戏
        this.notifyAll();
        this.flag=!flag;
    }
}
posted @ 2022-03-24 16:32  老李学Java  阅读(59)  评论(0)    收藏  举报