wait、notify 模拟queue

package com.bjsxt.base.queue;

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

public class Myqueue {
	
	private  final  LinkedList<Object> list = new LinkedList<Object>();
	
	private AtomicInteger count = new AtomicInteger();
	
	private final int minSize = 0;
	
	private final int maxSize;
	
	public Myqueue(int size){
		this.maxSize = size;
	}
	private final Object lock = new Object();
	
	public void put(Object obj){
		synchronized (lock) {
			while(count.get() == maxSize){
				try {
					lock.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			list.add(obj);
			count.incrementAndGet();
			System.out.println("新加入的元素:"+obj);
			System.out.println("剩余:"+count.get());
			lock.notify();
		}
	}
	public Object take(){
		Object ret = null;
		synchronized (lock) {
			while(count.get() == this.minSize){
				try {
					lock.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			ret = list.removeFirst();
			count.decrementAndGet();
			lock.notify();
			System.out.println("拿元素:"+ret);
			System.out.println("剩余:"+count.get());
		}
		return ret;
	}
	public int getSize(){
		return count.get();
	}
	
	public static void main(String[] args) {
		final Myqueue mq = new Myqueue(5);
		mq.put("a");
		mq.put("b");
		mq.put("c");
		mq.put("d");
		mq.put("e");
		System.out.println("当前容器长度 "+mq.getSize());
		
		
		new Thread(new Runnable(){
			@Override
			public void run() {
				mq.put("1");
				mq.put("2");
			}
		}).start();
	   try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   new Thread(new Runnable(){
			@Override
			public void run() {
				for(;;){
				   try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					mq.take();
				}
				
			}
		}).start();
	   try {
		Thread.sleep(20000);
	} catch (InterruptedException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	   new Thread(new Runnable(){
			@Override
			public void run() {
				mq.put("10");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mq.put("20");
			}
		}).start();
	   try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

猜你喜欢

转载自barabbas.iteye.com/blog/2416173