zoukankan      html  css  js  c++  java
  • 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();
    	
    	}
    }
    

      

  • 相关阅读:
    delphi xe10 FMX 启动参数
    delphi xe6 JSON 测试
    oracle实现http请求,oracle发送http请求。
    ORACLE存储过程调用Web Service
    新搭建的iis服务器,运行网站报 System.BadImageFormatException:未能加载文件或程序集”....“或它的某一个依赖项。
    c#的http请求工具类核心代码
    vue-cli3 取消关闭eslint 校验代码
    quartz.net数据库持久化教程
    sql备份一张表的数据
    iis 长期无访问导致定时任务不执行的解决方案
  • 原文地址:https://www.cnblogs.com/javabigdata/p/6952914.html
Copyright © 2011-2022 走看看