线程通信

197 阅读3分钟

应用场景

  • 应用场景: 生产者和消费者问题
  • 这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间互相依赖,互为条件。
  • 对于生产者,没有生产产品之前,要通知消费者等待。而生产了产品之后,又需要马上通知消费者消费。
  • 对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费。
  • 在生产者消费问题中,仅有synchronized是不够的
    1. synchronized可阻止并发更新同一个共享资源,实现同步
    2. synchronized不能用来实现不同线程之间的消息传递(通信)

线程通信

  • Java提供了几个方法解决线程之间的通信问题

    • wait() : 表示线程一直等待,知道其他线程通知,与sleep()不同,会释放锁。
    • wait(long timeout) : 指定等待的毫秒数
    • notify() : 唤醒一个处于等待状态的线程
    • notifyAll() : 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度。
  • 注意 : 均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常lllegalMonitorStateException

  • 生产者消费者问题-管程法

package com.Thread.lock;

//管程法实现生产者消费者问题
public class TestPC {

    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        Productor productor1 = new Productor(buffer, "P1");
        Productor productor2 = new Productor(buffer, "P2");
        Productor productor3 = new Productor(buffer, "P3");

        Consumer consumer = new Consumer(buffer,"C1");

        productor1.start();
        productor2.start();
        productor3.start();
        consumer.start();
    }
}

//生产者
class Productor extends Thread{
    private Buffer buffer;

    public Productor(Buffer buffer,String name){
        super(name);
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Chicken chicken = new Chicken(i);
            System.out.println(Thread.currentThread().getName() + "--生产了第" + i + "只鸡");
            try {
                buffer.push(chicken);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//消费者
class Consumer extends Thread{
    private Buffer buffer;

    public Consumer(Buffer buffer,String name){
        super(name);
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                Chicken chicken = buffer.pop();
                System.out.println(Thread.currentThread().getName() + "--消费了第" + chicken.getId() + "只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//产品
class Chicken{
    private int id;

    public Chicken(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}
//缓冲区
class Buffer{
    Chicken[] chickens = new Chicken[10];
    int count = 0;

    //放入产品
   public synchronized void push(Chicken chicken) throws InterruptedException {
       //如果容器满了,通知消费者消费
       if (count == chickens.length){
            //通知消费者消费,生产者等待
           this.wait();
        }
       //如果容器没有满,继续生产
       chickens[count] = chicken;
       count ++;

       //通知消费者消费
       this.notifyAll();
   }

   //消费产品
    public synchronized Chicken pop() throws InterruptedException {
       //判断是否能消费
        if (count == 0){
            //等待生产者生产,消费者等待
            this.wait();
        }
        //能消费了,
        count --;
        Chicken chicken = chickens[count];

        //通知生产者生产
        this.notifyAll();
       return chicken;
    }
}
  • 生产者消费者问题-信号灯法(设置标记位)
package com.Thread.lock;
//生产者消费者问题--信号灯法(设置标记位)
public class TestPC2 {
    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 % 2 == 0){
                tv.play("Java-从入门到入土");
            }else {
                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 voice;
    boolean flag = true;

    public synchronized void play(String voice){
        if (!flag){
            try {
                //演员等待
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了:" + voice);
        //通知观众观看
        this.notifyAll();
        this.voice = voice;
        this.flag = !this.flag;
    }

    public synchronized void watch(){
        if (flag){
            try {
                //观众等待
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("观众观看了:" + this.voice);
        //通知演员表演
        this.notifyAll();
        this.flag = !this.flag;
    }
}