java实现的生产者与消费者

定义生产者类、消费者类和共享队列


//Producer.java文件
class Producer extends Thread {
    Queue q;

    Producer(Queue q)
    {
        this.q = q;
    }

    public void run()
    {
        for (int i = 1;i < 5; i++)
        {
            q.put(i);
        }
    }
}

class Consumer extends Thread {
    Queue q;

    Consumer(Queue q)
    {
        this.q = q;
    }
    public void run()
    {
        while(true)
        {
            q.get();
        }
    }
}

class Queue {            //共享队列的目的用于保存生产者生产和消费者消费的共享数据
    int value = 0;
    boolean isEmpty = true;

    public synchronized void put(int v)
    {
        if (!isEmpty)
        {
            try {
                System.out.println("生产者等待");
                wait();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        value+=v;
        isEmpty = false;
        System.out.println("生产者共生产数量:"+v);
        notify();
    }

    public synchronized int get()
    {
        if(isEmpty)
        {
            try {
                System.out.println("消费者等待");
                wait();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        value--;
        if (value < 1)
        {
            isEmpty = true;
        }
        System.out.println("消费者消费一个,剩余:"+value);
        notify();
        return value;
    }
}

//ThreadCommunication.java文件
public class ThreadCommunication {
    public static void main(String[] args)
    {
        Queue q = new Queue();
        Producer p = new Producer(q);
        Consumer c = new Consumer(q);

        c.start();
        p.start();
    }
}

你可能感兴趣的:(java实现的生产者与消费者)