• 生产者消费者阻塞队列


    package html;
    
    import java.util.LinkedList;
    import java.util.List;
    
    public class KF {
    
        public static void main(String[] args) {
            BlockList list = new BlockList(10);
            new Thread(new Productor(list)).start();
            new Thread(new Consumer(list)).start();
        }
    
        static class Productor implements Runnable {
            BlockList list;
    
            public Productor(BlockList list) {
                this.list = list;
            }
    
            @Override
            public void run() {
                int i = 0;
                while (true) {
                    System.err.println("put:" + i);
                    list.put(i++);
                }
            }
        }
    
        static class Consumer implements Runnable {
            BlockList list;
    
            public Consumer(BlockList list) {
                this.list = list;
            }
    
            @Override
            public void run() {
                while (true) {
                    Object obj = list.get();
                    System.err.println("get:" + obj);
                }
            }
        }
    }
    
    class BlockList {
        List<Object> list;
        int capacity;
    
        public BlockList(int capacity) {
            this.capacity = capacity;
            list = new LinkedList<>();
        }
    
        public boolean put(Object obj) {
            synchronized (list) {
                while (list.size() >= capacity) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                list.add(obj);
                list.notifyAll();
            }
    
            return false;
        }
    
        public Object get() {
            Object obj = null;
            synchronized (list) {
                while (list.isEmpty()) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
    
                obj = list.remove(0);
                list.notifyAll();
            }
            return obj;
        }
    
    }
  • 相关阅读:
    iOS离屏渲染简书
    iOS Waxpatch项目(动态更新)
    waxpatch修改任意类的用法
    ios waxpatch lua语法
    ios WaxPatch热更新原理
    WaxPatch中demo注意问题
    ios wax热更新之安装wax(xcode7.3.1)
    获取第三方键盘高度(包括自带键盘高度)
    25个增强iOS应用程序性能的提示和技巧(高级篇)(2)
    JS基础_一元运算符
  • 原文地址:https://www.cnblogs.com/jpit/p/7404557.html
Copyright © 2020-2023  润新知