读者写者java多线程_秒杀多线程第十一篇 读者写者问题(续)

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();

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值