三种方式实现生产者消费者模式

使用synchronized关键字

package com.example.interview.multi_thread;

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

public class PACTest {
    static class Producer implements Runnable {

        List<Integer> list;

        public Producer(List<Integer> list) {
            this.list = list;
        }

        @Override
        public void run() {
            while (true) {
                // 休眠防止释放锁之后再次和其他线程产生竞争
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (list) {
                    while (list.size() >= 10) {
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // 模拟生产时间
                    try {
                    Thread.sleep(300);
                    } catch (InterruptedException e) {
                    e.printStackTrace();
                    }
                    int random = new Random().nextInt(10);
                    list.add(random);
                    System.out.println(Thread.currentThread().getName() + "生产了" + random + " 仓库:" + list.size());
                    list.notifyAll();
                }
            }
        }
    }

    static class Consumer implements Runnable {

        List<Integer> list;

        public Consumer(List<Integer> list) {
            this.list = list;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (list) {
                    while (list.size() <= 0) {
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    // 模拟消费时间
                    try {
                        Thread.sleep(700);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    int a = list.remove(0);
                    System.out.println(Thread.currentThread().getName() + "消费了" + a + " 仓库:" + list.size());
                    list.notifyAll();
                }
            }
        }
    }



    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();

        Producer producer = new Producer(list);
        Producer producer2 = new Producer(list);
        Consumer consumer = new Consumer(list);
        Consumer consumer2 = new Consumer(list);

        Thread t1 = new Thread(producer);
        Thread t2 = new Thread(producer2);
        Thread t3 = new Thread(consumer);
        Thread t4 = new Thread(consumer2);

        t1.setName("生产者线程1");
        t2.setName("生产者线程2");
        t3.setName("消费者线程1");
        t4.setName("消费者线程2");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

使用ReentrantLock实现一

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ProAndConTest05 {
    private static int count = 0;
    private int maxNum = 5;
    ReentrantLock lock = new ReentrantLock();
    Condition producerCondition = lock.newCondition();
    Condition consumerCondition = lock.newCondition();


    class Producer implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                try {
                    while (count >= maxNum) {
                        producerCondition.await();
                    }
                    count++;
                    System.out.println(Thread.currentThread().getName() + "生产者生产,目前总共有" + count);
                    consumerCondition.signalAll();
                }catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    class Consumer implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(700);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                try {
                    while (count <= 0) {
                        consumerCondition.await();
                    }
                    count--;
                    System.out.println(Thread.currentThread().getName() + "消费者消费,目前总共有" + count);
                    producerCondition.signalAll();
                }catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }
    }


    public static void main(String[] args) {
        ProAndConTest05 test = new ProAndConTest05();

        new Thread(test.new Consumer()).start();
        new Thread(test.new Consumer()).start();
        new Thread(test.new Producer()).start();
        new Thread(test.new Producer()).start();
    }
}

使用ReentrantLock实现二

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProAndConTest02 {
    static class Producer implements Runnable {

        List<Integer> list;
        Lock lock;
        Condition noProductCondition;
        Condition fullProductCondition;

        public Producer(List<Integer> list, Lock lock, Condition noProductCondition, Condition fullProductCondition) {
            this.list = list;
            this.lock = lock;
            this.noProductCondition = noProductCondition;
            this.fullProductCondition = fullProductCondition;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                try {
                    while (list.size() >= 3) {
                        noProductCondition.await();
                    }
                    int random = new Random().nextInt(10);
                    list.add(random);
                    System.out.println(Thread.currentThread().getName() + "生产了" + random + " 【库存量:】" + list.size());
                    fullProductCondition.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    static class Consumer implements Runnable {

        List<Integer> list;
        Lock lock;
        Condition noProductCondition;
        Condition fullProductCondition;

        public Consumer(List<Integer> list, Lock lock, Condition noProductCondition, Condition fullProductCondition) {
            this.list = list;
            this.lock = lock;
            this.noProductCondition = noProductCondition;
            this.fullProductCondition = fullProductCondition;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(700);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                try {
                    while (list.size() <= 0) {
                        fullProductCondition.await();
                    }
                    int i = list.remove(0);
                    System.out.println(Thread.currentThread().getName() + "消费了" + i + " 【库存量:】" + list.size());
                    noProductCondition.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }

        }
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Lock lock = new ReentrantLock();
        Condition noProductCondition = lock.newCondition();
        Condition fullProductCondition = lock.newCondition();

        new Thread(new Producer(list, lock, noProductCondition, fullProductCondition)).start();
        new Thread(new Producer(list, lock, noProductCondition, fullProductCondition)).start();
        new Thread(new Consumer(list, lock, noProductCondition, fullProductCondition)).start();
        new Thread(new Consumer(list, lock, noProductCondition, fullProductCondition)).start();

//        Producer pro = new Producer(list, lock, noProductCondition, fullProductCondition);
//        Consumer con = new Consumer(list, lock, noProductCondition, fullProductCondition);
//        Thread t1 = new Thread(pro);
//        Thread t2 = new Thread(con);
//        t1.setName("生产者线程");
//        t2.setName("消费者线程");
//        t1.start();
//        t2.start();
    }
}

使用BlockingQueue使用

package com.example.interview.multi_thread;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProAndConTest03 {
    static class Producer implements Runnable {

        BlockingQueue<Integer> queue;

        public Producer(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(200);
                    int i = new Random().nextInt(10);
                    queue.put(i);
//                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "生产了" + i + " 【库存量:】" + queue.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    static class Consumer implements Runnable {
        BlockingQueue<Integer> queue;

        public Consumer(BlockingQueue<Integer> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(500);
                    int i = queue.take();
//                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "消费了" + i + "        【库存量:】" + queue.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {

        BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(4);
        new Thread(new Producer(queue)).start();
        new Thread(new Producer(queue)).start();
        new Thread(new Consumer(queue)).start();
        new Thread(new Consumer(queue)).start();
//        Producer pro = new Producer(queue);
//        Consumer con = new Consumer(queue);
//        Thread t1 = new Thread(pro);
//        Thread t2 = new Thread(con);
//        t1.setName("生产者线程");
//        t2.setName("消费者线程");
//        t1.start();
//        t2.start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值