LinkedBlockingDeque 阻塞队列(当队列中存满10个数据之后开始获取数据)

package com.java.basis.threads;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDequeTest {
	public static void main(String[] args) throws InterruptedException {
		LinkedBlockingDequeTest l = new LinkedBlockingDequeTest();
		ExecutorService e = Executors.newFixedThreadPool(2);
		queue q = l.new queue();
		put p = l.new put(q);
		get g = l.new get(q);
		e.execute(p);
		e.execute(g);
		e.shutdown();
	}
	public class get implements Runnable {
		
		private queue q = null;

		public get(queue q) {
			this.q = q;
		}
		
		public void run() {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			while (true) {
				try {
					if(q.size()==10){
					Object o = q.getfromqueue();
					System.out.println("阻塞栈中取出最后一个数据" + o.toString());
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	public class put implements Runnable {
		private queue q = null;
		public put(queue q) {
			this.q = q;
		}

		int i = 0;

		public void run() {
			while (true) {
				i++;
				// 将指定元素添加到此阻塞栈中,如果没有可用空间,将一直等待(如果有必要)。
				try {
					
					System.out.println("往阻塞栈中存放数据" + i);
					q.addtoqueue(i);
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	// 队列
	public class queue {
		BlockingDeque bDeque = new LinkedBlockingDeque(10);
		
		public int size(){
			return bDeque.size();
		}
		
		// 往队列中放数据
		public void addtoqueue(int i) throws InterruptedException {
			
			bDeque.putFirst(i);
		}

		// 从队列中取出数据
		public Object getfromqueue() throws InterruptedException {
			return bDeque.takeFirst();
		}

	}

}

  

posted @ 2016-10-14 17:27  fliay  阅读(970)  评论(0)    收藏  举报