我写了future pattern的一个类FutureQue,使用ReentrantLock进行同步,Condition进行条件等待.
测试发现Condition,ReentrantLock在多个线程操作同一资源时失去作用,代码如下:
import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class FutureQue<E> {
public FutureQue() {
iQue = new ArrayList<E>();
iLock = new ReentrantLock();
iIsEmptyCond = iLock.newCondition();
}

public void put( E aE ) {
iLock.lock();

try {
int oldSize = iQue.size();

iQue.add( aE ); 

if ( 0 == oldSize )
iIsEmptyCond.signal();
} finally {
iLock.unlock();
}
}

public E get() throws InterruptedException {
iLock.lock();

try {
System.out.println( Thread.currentThread().getId() + " size=" + iQue.size() );

if ( 0 == iQue.size() )  {
System.out.println( "wait" );
iIsEmptyCond.await();
}

int lastIndex = iQue.size() - 1;

System.out.println( Thread.currentThread().getId() + 
"  size1=" + iQue.size() );

E e = iQue.get( lastIndex );

iQue.remove( lastIndex );

return e;
} finally {
iLock.unlock();
}
}

public static FutureQue<Object> instance() {
return SingletonHolder.iSelf;
}

private static class SingletonHolder {
private static final FutureQue<Object> iSelf = new FutureQue<Object>();
}

private volatile ArrayList<E>  iQue;

private volatile Condition     iIsEmptyCond;
private volatile Lock          iLock;
}测试代码:
class Producer extends Thread {
public void run() {
for ( ; ; ) { 
FutureQue.instance().put( "aaaa" );
System.out.println("Producer [" + this.getId() + "] put" );
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}class Consumer extends Thread {
public void run() {
for (;;) {
try {
System.out.println("Consumer [" + this.getId() + "] get:" + FutureQue.instance().get()  );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}public class FutureQueTest {
public static void main(String[] args) {
Producer p = new Producer();
Producer p1 = new Producer();
Consumer c = new Consumer();
Consumer c1 = new Consumer();

p1.start();
p.start();
c.start();
c1.start();
}
}运行时,FutureQue的get出现异常.该如何解决这个问题了?谢谢!!!