手写生产者和消费者

使用object的wait和notify方法

生产者

import java.util.List;

public class Producer implements Runnable {

    private List<String> queue;

    public void run() {
        synchronized (queue) {
            while (true) {
                while (queue.size() == MqTest.MAX_COUNT) {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "在生产!!!!");
                queue.add(String.valueOf(Math.random()));
                queue.notifyAll();
            }
        }
    }

    public List<String> getQueue() {
        return queue;
    }

    public void setQueue(List<String> queue) {
        this.queue = queue;
    }
}

  

消费者

import java.util.List;

public class Comsumer implements Runnable {
    private List<String> queue;

    public void setQueue(List<String> queue) {
        this.queue = queue;
    }

    public List<String> getQueue() {
        return queue;
    }

    public void run() {
        synchronized (queue) {
            while (true) {
                while (queue.size() == 0) {
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "在消费!!!!");
                queue.remove(0);
                queue.notifyAll();
            }

        }
    }
}

生产过程

import java.util.ArrayList;
import java.util.List;

public class MqTest {

    public static final int MAX_COUNT = 10;

    public static void main(String[] args) {
        List<String> queue = new ArrayList<String>();
        Producer producer = new Producer();
        producer.setQueue(queue);
        Thread t1 = new Thread(producer);
        t1.setName("生产者1");

        Producer producer1 = new Producer();
        producer1.setQueue(queue);
        Thread t3 = new Thread(producer1);
        t3.setName("生产者2");

        Producer producer2 = new Producer();
        producer2.setQueue(queue);
        Thread t4 = new Thread(producer2);
        t4.setName("生产者3");



        Comsumer comsumer = new Comsumer();
        comsumer.setQueue(queue);


        Thread t2 = new Thread(comsumer);
        t2.setName("消费者1");

        Comsumer comsumer1 = new Comsumer();
        comsumer1.setQueue(queue);


        Thread t5 = new Thread(comsumer1);
        t5.setName("消费者2");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}
02-09 22:03