• java多线程系列10 阻塞队列模拟


    接下来的几篇博客会介绍下juc包下的相关数据结构

    包含queuelistmap

    这篇文章主要模拟下阻塞队列。

    下面是代码

    import java.util.LinkedList;
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class MyBlockingQueue<T>  {
    
    	private final LinkedList<T> queue = new LinkedList<>();
    	private final AtomicInteger size = new AtomicInteger(0);
    	private final Object lock = new Object();
    	private final int maxSize ;
    	public MyBlockingQueue(int maxSize) {
    		this.maxSize = maxSize;
    	}
    
    	public void add(T t) {
    		synchronized (lock) {
    			while (size.get() == maxSize) {
    				try {
    					lock.wait();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    			queue.add(t);
    			size.incrementAndGet();
    			lock.notifyAll();
    		}
    
    	}
    
    	public T poll() {
    
    		T result = null;
    		synchronized (lock) {
    			while (size.get() == 0) {
    				try {
    					lock.wait();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    				
    			}
    			result = queue.removeFirst();
    			size.decrementAndGet();
    			lock.notifyAll();
    		}
    		return result;
    	}
    	public int getSize()
    	{
    		return size.get();
    	}
    	
    	public static void main(String[] args) {
    		final MyBlockingQueue<String> queue  = new MyBlockingQueue<>(1);
    		Thread t1 = new Thread(new Runnable() {
    			@Override
    			public void run() {
    				queue.add("h");
    				queue.add("j");
    				queue.add("h1");
    				queue.add("j1");
    				queue.add("h2");
    				queue.add("j2");
    			}
    		}, "t1");
    		
    		Thread t2 = new Thread(new Runnable() {
    			@Override
    			public void run() {
    				try {
    					while(true)
    					{
    						Thread.sleep(1000);
    						System.out.println("t2取走的元素为:" + queue.poll());
    					}
    				
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    		}, "t2");
    		Thread t3 = new Thread(new Runnable() {
    			@Override
    			public void run() {
    				try {
    					while(true)
    					{
    						Thread.sleep(1000);
    						System.out.println("t3取走的元素为:" + queue.poll());
    					}
    				
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    		}, "t3");
    		t1.start();
    		t2.start();
    		t3.start();
    	
    	}
    }
    

      

  • 相关阅读:
    值币转换编程总结
    打印沙漏编程总结
    Leetcode每日一题 面试题 17.21. 直方图的水量
    VS2017-OPENGL配置glfw+glad
    OpenGL(二) 绘制一个三角形
    OpenGL(一) 渲染循环创建窗口
    Leetcode每日一题 1006.笨阶乘
    Leetcode每日一题 90.子集 II
    Leetcode每日一题 190.颠倒二进制位
    Leetcode 第243场周赛 创新奇智&力扣
  • 原文地址:https://www.cnblogs.com/javabigdata/p/6952914.html
Copyright © 2020-2023  润新知