packagecom.multithread.readwrite;importjava.util.ArrayList;importjava.util.LinkedList;importjava.util.List;importjava.util.Queue;importjava.util.concurrent.BrokenBarrierException;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.CyclicBarrier;importjava.util.concurrent.Executor;importjava.util.concurrent.Executors;importjava.util.concurrent.Semaphore;importcom.multithread.main.ExampleInterface;importcom.multithread.prosumer.ProducerThread;/*** 1.写者要等待所有读者读完才能继续写入。
* 2.所有读者要等待写者写完才能继续读取。
* 3.读者这件可以共享读取文件。
*
*
*
**/
public class ReaderWriterExample extendsExampleInterface {public static final int READ_THREAD_SIZE = 4;public static final int BUFFER_LENGTH = 100;public List g_productor = new ArrayList();public CountDownLatch mReaderLatch = newCountDownLatch(READ_THREAD_SIZE);public Semaphore mWriteSema = newSemaphore(READ_THREAD_SIZE);public boolean bStopFlag = false;public CountDownLatch mLatchDown = new CountDownLatch(1+READ_THREAD_SIZE);public CountDownLatch mLatchStart = new CountDownLatch(1+READ_THREAD_SIZE);
@Overridepublic voidstartDemo() {//TODO Auto-generated method stub
try{
initReadNone();
bStopFlag= false;
Executor mEcecutor= Executors.newFixedThreadPool(1+READ_THREAD_SIZE);
mEcecutor.execute(new WriteThread(this,"Writer"));for(int i=1;i<=READ_THREAD_SIZE;i++)
{
mEcecutor.execute(new ReadThread(this,"Reader"+i));
}
mLatchStart.await();
System.out.println("All Thread is runnning");
mLatchDown.await();
System.out.println("All Thread is Down");
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}public voidwaitReaderEnd()
{//多个read End,using countdownlatch
try{
mReaderLatch.await();
mReaderLatch= newCountDownLatch(READ_THREAD_SIZE);
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}public voidsingalWriteEnd(){
mWriteSema.release(READ_THREAD_SIZE);
}public voidwaitWriteEnd(){try{
mWriteSema.acquire();
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}public voidsingalReadEnd(){
mReaderLatch.countDown();
}public voidinitReadNone(){try{
mWriteSema.acquire(READ_THREAD_SIZE);for(int i=0;i
{
mReaderLatch.countDown();
}
}catch(InterruptedException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}