• java多线程实现简单队列


      1.创建Queue.java

    public class Queue {
    	
    	private LinkedList<Object> list = new LinkedList<Object>() ;
    	
    	private final int minSize = 0 ; ;
    	
    	private final int maxSize ;
    	
    	private AtomicInteger count = new AtomicInteger(0) ;
    	
    	public Queue(int size){
    		this.maxSize = size ;
    	}
    	private final Object lock = new Object() ;
    	
    	public void put(Object o){
    		synchronized(lock){
    			while(size() == this.maxSize){
    				try {
    					lock.wait();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    			list.add(o) ;
    			//计数器增加
    			count.incrementAndGet() ;
    			//通知唤醒
    			lock.notify();
    		}
    	}
    	
    	
    	private int size(){
    		return count.get() ;
    	}
    	
    	public Object take(){
    		Object res = null ;
    		synchronized(lock){
    			while(size() == this.minSize){
    				try {
    					lock.wait();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    			res = list.removeFirst();
    			//计数器减1
    			count.decrementAndGet() ;
    			lock.notify();
    		}
    		return res ;
    		
    	}
    	
    	public static void main(String[] args) {
    		
    		final Queue mq = new Queue(3) ;
    		
    		mq.put("a");
    		mq.put("b");
    		mq.put("c");
    		
    		new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				mq.put("g");
    				System.out.println("put1 secceseful");
    				mq.put("f");
    				System.out.println("put2 secceseful");
    			}
    		}).start();
    		
    		
    		new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				System.out.println("take value = "+mq.take() );
    			}
    		}).start();
    		
    		
    	}
    }
    

      运行结果如下:

    take value = a
    put1 secceseful
    

      执行第一个put的时候由于队列容量已经满了,所以线程阻塞。另一个线程take之后,阻塞的线程继续执行put成功。

  • 相关阅读:
    android 发短信
    如何判断一个Div是否可视区域,判断div是否可见
    java arrayCopy
    Java 正则表达式 向前、向后匹配
    postgres 正则表达式
    java 分析方法调用过程
    chrome 模拟点击
    Java获取NTP网络时间
    Android对话框与Activity共存时的异常
    Android代码混淆
  • 原文地址:https://www.cnblogs.com/dquery/p/6395553.html
Copyright © 2020-2023  润新知