一段阻塞队列代码的纠错与优化

本文探讨了阻塞队列中出现的一个等待条件检查错误,并提供了修正方案及优化后的代码。通过使用synchronized关键字和wait/notify机制确保线程安全,避免了因条件变化而可能导致的空值返回等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的代码在某处发现后,立马发现存在问题。

public class BlockingQ {

	private Object notEmpty = new Object();
	private Object notFull = new Object();
	private Queue<Object> linkedList = new LinkedList<Object>();
	private int maxLength = 10;
	
	public Object take() throws InterruptedException{
		synchronized(notEmpty){
			if(linkedList.size() == 0){
				notEmpty.wait();
			}
			synchronized(notFull){
				if(linkedList.size() == maxLength){
					notFull.notifyAll();
				}
				return linkedList.poll();
			}
		}
	}
	
	public void offer(Object object) throws InterruptedException{
		synchronized(notEmpty){
			if(linkedList.size() == 0){
				notEmpty.notifyAll();
			}
			synchronized(notFull){
				if(linkedList.size() == maxLength){
					notFull.wait();
				}
				linkedList.add(object);
			}
		}
	}
}

最简单的情况就是一个生产者,两个消费者,
			if(linkedList.size() == 0){
				notEmpty.wait();
			}

上面的if语句在第二线程重新获取锁后,进来的时候不会再次判断是否有消费元素,会直接返回null。

	public Object take() throws InterruptedException{
		synchronized(notEmpty){
			while(linkedList.size() == 0){
				notEmpty.wait();
			}
			synchronized(notFull){
				if(linkedList.size() == maxLength){
					notFull.notifyAll();
				}
				return linkedList.poll();
			}
		}
	}

修正代码如上面所示。

整个代码主要用作示例,所以代码上存在很冗余的点,下面是代码优化后的版本:

public class SimpleBlockingQ {
	private Queue<Object> linkedList = new LinkedList<Object>();
	private int maxLength = 10;
	
	public synchronized Object take() throws InterruptedException{
		while(linkedList.size() == 0){
			wait();
		}
		notifyAll();
		return linkedList.poll();
	}
	
	public synchronized void offer(Object object) throws InterruptedException{
		notifyAll();
		if(linkedList.size() == maxLength){
			wait();
		}
		linkedList.add(object);
	}
}

从性能上优化,可以参考《一种简单无锁队列的实现》和《无锁同步栈实现》。

下面是测试代码:

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 天水
 * @date 2013-4-12 下午03:44:15
 */
public class BlockingQTest {

	public static AtomicInteger index = new AtomicInteger(0);
	
	public static void main(String[] args){
		int tCount = 10; // thread count
		
		final BlockingQ BQ = new BlockingQ();
		final SimpleBlockingQ SBQ = new SimpleBlockingQ();
		
		// provider
		Runnable pr = new Runnable(){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(100);
						
						int tindex = index.getAndIncrement();
						//BQ.offer(tindex);
						//System.out.println("BQ offer: " + tindex);
						SBQ.offer(tindex);
						System.out.println("SBQ offer: " + tindex);
						
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			}
		};
		// consumer
		Runnable cr = new Runnable(){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(100);
					
						//System.out.println("BQ take: " + BQ.take());
						System.out.println("SBQ take: " + SBQ.take());		

						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		
		for(int i=0; i<tCount; i++){
			new Thread(cr).start();
		}
		
		for(int i=0; i<tCount; i++){
			new Thread(pr).start();
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值