下面的代碼在某處發現後,立馬發現存在問題。
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();
}
}
}