55线程间通信(消费生产模式)

线程间通信:
*wait()方法:中断方法的执行,使线程等待
*notify()方法:唤醒处于等待的某一个线程,使其结束等待
*notifyAll()方法:唤醒所有处于等待的线程,使它们结束等待
注意:notify()方法是随机唤醒一个线程,notifyAll()方法是唤醒所有线程,一般用notifyAll()

生产者消费者模式:
这里想要实现的功能,生产者生产内容,消费者消费内容,如果生产者遇到内容没有消费,就等待,并通知消费者,如果消费者遇到没有内容,就通知生产者。

package com.imooc.queue;

public class Queue {
    private int n;
    boolean flag=false;
    
    public synchronized int get() {
        if(!flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("消费:"+n);
        flag=false;//消费完毕,容器中没有数据
        notifyAll();
        return n;
    }

    public synchronized void set(int n) {
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("生产:"+n);
        this.n = n;
        flag=true;//生产完毕,容器中已经有数据
        notifyAll();
    }
    
}

package com.imooc.queue;

public class Consumer implements Runnable{
    Queue queue;
    Consumer(Queue queue){
        this.queue=queue;
    }

    @Override
    public void run() {
        while(true){
            queue.get();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
}

package com.imooc.queue;

public class Producer implements Runnable{
    Queue queue;
    Producer(Queue queue){
        this.queue=queue;
    }

    @Override
    public void run() {
        int i=0;
        while(true){
            queue.set(i++);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

}

package com.imooc.queue;

public class Test {

    public static void main(String[] args) {
        Queue queue=new Queue();
        new Thread(new Producer(queue)).start();
        new Thread(new Consumer(queue)).start();
    }

}

分析如果不加notifyAll();出现死锁的情况
1.消费者消费完,flag = false
2.消费者继续消费,进入等待状态
3.生产者生产完,flag = true
4.生产者继续生产,进入等待状态
5.死锁形成

你可能感兴趣的:(55线程间通信(消费生产模式))