利用synchronized作为通信载体,wait/notify方法实现生产者-消费者模式

90 阅读1分钟

生产者:

public class Producer implements Runnable{
    private Queue<String> bags;
    private int size;
    public Producer(Queue<String> bags, int size) {
        this.bags = bags;
        this.size = size;
    }


    @Override
    public void run() {
        int i = 0;
        while (true) {
            i++;
            synchronized(bags) {
                if (bags.size() == size) {
                    System.out.println("bags满了");
                    try {
                        bags.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("生产者-生产:bag" + i);
                bags.add("bag" + i);
                bags.notifyAll();

            }
        }
    }
}

消费者:

public class Customer implements Runnable{
    private Queue<String> bags;
    private int size;

    public Customer(Queue<String> bags, int size) {
        this.bags = bags;
        this.size = size;
    }

    @Override
    public void run() {
        while (true) {
            synchronized(bags) {
                if (bags.isEmpty()) {
                    System.out.println("bags为空");
                    try {
                        bags.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String bag = bags.poll();
                System.out.println("消费者-消费:" + bag);
                bags.notifyAll();
            }
        }
    }
}

测试类:

public class WaitNotify {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<String>();
        int size = 10;
        Producer p = new Producer(queue, size);
        Customer c = new Customer(queue, size);
        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);
        t1.start();
        t2.start();
    }
}