JDK5什么是新的堵塞队列线程(四)

一. 堵塞队列与普通队列:

队列是一种主要的数据类型,其典型特征是先进先出。

堵塞队列和普通队列的差别在于:

当队列为空时。从队列中获取元素的线程会被堵塞。直到其它的线程往空的队列里插入新的元素;

当队列是满的时。往队列里加入元素的操作会被堵塞。直到其它的线程从队列移除一个或多个元素。


上图中:线程1往堵塞队列里加入元素,而线程2从堵塞队列里移除元素

/**
 * 堵塞队列的简单实现
 */
public class BlockingQueue<T> {

	private List<T> queue = new LinkedList<T>();

	private int limit = 10;
	
	public BlockingQueue(){
	}
	
	public BlockingQueue(int limit) {
		this.limit = limit;
	}
	
	// 入队
	public synchronized void enqueue(T obj) throws InterruptedException { 
		while (this.queue.size() == this.limit) {
			wait();
		}
		if (this.queue.size() == 0) {
			notifyAll();
		}
		this.queue.add(obj);
	}
	
	// 出队
	public synchronized Object dequeue() throws InterruptedException {
		while (this.queue.size() == 0) {
			wait();
		}
		if (this.queue.size() == this.limit) {
			notifyAll();
		}
		return this.queue.remove(0);
	}
}

二. API实现:

BlockingQueue是一个接口,有下面实现类:

1. ArrayBlockQueue:一个由数组支持的有界堵塞队列,此队列遵循先进先出原则排序,创建其对象必须明白大小。

2. LinkedBlockQueue:一个可改变大小的堵塞队列,此队列遵循先进先出原则排序,创建其对象没有明白大小。并发程序中。性能稍差。

3. PriorityBlockingQueue: 类似LinkedBlockQueue,但其所含对象的排序不是先进先出,而是根据对象的自然排序顺序或构造函数所带的Comparator决定

4. SynchronousQueue:同步队列, 每插入一个必须等待还有一个线程移除。


以下代码用3个空间的队列来演示堵塞队列的功能和效果。

public class BlockingQueueTest {

	public static void main(String[] args) {
		
		// 堵塞队列类: 队列中能够存3个数据
		final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3);
		
		// 开启3个线程不断的存数据
		for (int i = 0; i < 3; i++) {
			new Thread() {
				public void run() {
					while (true) {
						try {
							Thread.sleep((long) Math.random() * 1000);
							System.out.println(Thread.currentThread().getName() + " 准备放数据。");
							queue.put(1); // 往队列中存数据
							System.out.println(Thread.currentThread().getName() 
									+ " 已经放了数据,队列眼下有: " + queue.size() + " 个数据!");
							Thread.sleep(1000);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}.start();
		}
		
		// 开启一个线程不断的取数据
		new Thread() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000);
						System.out.println(Thread.currentThread().getName() + " 准备取数据!

"); queue.take(); // 从队列中取数据 System.out.println(Thread.currentThread().getName() + " 已经取走数据,队列眼下有: " + queue.size() + " 个数据!

"); } catch (Exception e) { e.printStackTrace(); } } } }.start(); } }

Thread-1 准备放数据!

Thread-1 已经放了数据,队列眼下有: 1 个数据。 Thread-0 准备放数据! Thread-0 已经放了数据。队列眼下有: 2 个数据! Thread-2 准备放数据!

Thread-2 已经放了数据,队列眼下有: 3 个数据。 Thread-3 准备取数据。 Thread-3 已经取走数据,队列眼下有: 2 个数据! Thread-1 准备放数据! Thread-1 已经放了数据,队列眼下有: 3 个数据。 Thread-0 准备放数据。 Thread-2 准备放数据! Thread-3 准备取数据! Thread-3 已经取走数据,队列眼下有: 2 个数据! Thread-0 已经放了数据,队列眼下有: 3 个数据。 Thread-1 准备放数据! Thread-0 准备放数据! Thread-3 准备取数据!

Thread-3 已经取走数据。队列眼下有: 2 个数据! Thread-2 已经放了数据,队列眼下有: 3 个数据!


三. 堵塞队列实现同步通信

面试题:子线程打印2行信息,然后主线程打印4行信息。循环各打印5次

public class BlockingQueueCommunication {

	public static void main(String[] args) throws Exception {
		final Business business = new Business();
		
		// 子线程循环运行5次
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 5; i++) {
					try {
						business.sub(i);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		// 主线程循环运行5次
		for (int i = 1; i <= 5; i++) {
			business.main(i);
		}
	}

	static class Business {
		
		// 堵塞子线程的队列,里面仅仅能有一个数据。 超了就会堵塞
		BlockingQueue<Integer> subQueue = new ArrayBlockingQueue<Integer>(1);
		
		// 堵塞主线程的队列,里面仅仅能有一个数据, 超了就会堵塞
		BlockingQueue<Integer> mainQueue = new ArrayBlockingQueue<Integer>(1);
		
		// 这是一个匿名的构造方法。创建对象的时候就会调用它
		{
			try {
				System.out.println("我运行了,一上来就把main queue中放了一个数据");
				mainQueue.put(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		public void sub(int i) throws Exception {
			subQueue.put(1);
			for (int j = 0; j <= 1; j++) {
				System.out.println("sub thread sequence of  " + j + " ,loop of  " + i);
			}
			mainQueue.take(); // main线程释放堵塞,開始运行
		}

		public void main(int i) throws Exception {
			mainQueue.put(1);
			for (int j = 0; j <= 3; j++) {
				System.out.println("main thread sequence of  " + j + " ,loop of  " + i);
			}
			subQueue.take(); // sub线程释放堵塞,開始运行
		}
	}
}



版权声明:本文博主原创文章。博客,未经同意不得转载。

posted @ 2015-09-21 09:42  yxwkaifa  阅读(192)  评论(0编辑  收藏  举报