Java实现BlockingQueue队列(二)

之前写过Java实现阻塞队列 是以链表的形式实现的,最近闲着,又试了下数组形式的实现。直接上代码吧。

package com.xtli.queue;

import java.util.Random;

/*
 * 阻塞队列。put方法,take方法。
 * 数组实现。
 * 定义队列的head和tail:
 * head 指向第一个值;
 * tail 指向最后一个为null的下标;
 * 队列中的数量count
 * 
 */
public class MyBlockingQueue {
	private Object[] a = null;
	private int tail = 0;//tail指向最后一个为null的下标
	private int head = 0;//head指向第一个有值的下标
	private int count = 0;
	private MyBlockingQueue() {
		
	}
	private MyBlockingQueue(int size) {
		a = new Object[size];
	}
	public synchronized void put(Object obj) throws InterruptedException {
		while(isFull()) {
			System.out.println("【入队操作】阻塞,释放锁");
			wait();
		}
		System.out.println("【入队操作】获取锁");
		a[tail] = obj;
		if(++tail == a.length) {
			 tail = 0;
		}
		count++;		
		System.out.println("【入队操作】队列值:" + toString());
		notifyAll();
	}
	public synchronized Object take() throws InterruptedException {
		while(isEmpty()) {
			System.out.println("【出队操作】阻塞,释放锁");
			wait();
		}
		System.out.println("【出队操作】获取锁");
		System.out.println("【出队操作】队列值:" + toString());
		Object re = a[head];
		a[head] = null;
		if(++head == a.length) {
			head = 0;
		}
		count--;
		notifyAll();
		System.out.println("take值:" + re);
		return re;
	}
	public boolean isEmpty() {
		return count == 0;
	}
	
	public boolean isFull() {
		return count == a.length;
	}
	public String toString() {
		StringBuffer sb = new StringBuffer();
		if(count > 0) {
			for(int i=0;i<a.length;i++) {
				sb.append(a[i]+",");
			}
		}
		return sb.toString();
	}
	public static void main(String[] args) throws InterruptedException {
		final MyBlockingQueue bq = new MyBlockingQueue(10);
		Thread con = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while(true) {
						Object re = bq.take();
						Thread.sleep(1000);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			}
		);
		con.start();
		
		
		Thread pro = new Thread(new Runnable() {
			@Override
			public void run() {
					try {
						while(true) {
							Random r = new Random();
							Integer a = new Integer(r.nextInt());
							bq.put(a);
						}
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		);
		pro.start();
		
	}
}



运行之后,大概就是下面这个样子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值