Android面试笔记——生产者消费者模式

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ProducerAndConsumer {
    public static void main(String[] args) {
        //准备15个线程,5个用于生产者,10个用于消费者
        ExecutorService executorService = Executors.newFixedThreadPool(15);
        ArrayList<Integer> list  = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            executorService.submit(new Producer(list,10));
        }
        for (int i = 0; i < 10; i++) {
            executorService.submit(new Consumer(list));
        }
    }


    public static class Producer implements Runnable{
        final ArrayList<Integer> list;
        //产品的最大数量
        int maxProductions;
        //在构造函数中传入列表
        public Producer(ArrayList<Integer> list, int maxProductions) {
            this.list = list;
            this.maxProductions = maxProductions;
        }


        @Override
        public void run() {
            //死循环
            while (true){
                //对list加锁
                synchronized (list){
                    //判断产品是否达到最大数量
                    //注意这里不要用if,要用while
                    //因为当前线程被唤醒时,如果其他线程已经率先完成生产(此时数量已经达到最大),此线程再生产就超过了最大数量
                    while(list.size()==maxProductions){
                        System.out.println("生产者停止生产,"+"产品数量:"+list.size());
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("生产者开始生产,"+"产品数量:"+list.size());
                    }
                    list.add(1);
                    list.notifyAll();
                    System.out.println("生产者生产完成,"+"产品数量:"+list.size());
                }
            }
        }
    }
    public static class Consumer implements Runnable{
        final ArrayList<Integer> list;

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

        @Override
        public void run() {
            while (true){
                synchronized (list){
                    //判断产品数量是否为0,同样用while判断
                    while(list.size()==0){
                        System.out.println("消费者停止消费,"+"产品数量:"+list.size());
                        try {
                            list.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("消费者开始消费,"+"产品数量:"+list.size());
                    }
                    list.remove(0);
                    list.notifyAll();
                    System.out.println("消费者消费完成,"+"产品数量:"+list.size());
                }

            }
        }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容