欢迎来到天天文库
浏览记录
ID:51710288
大小:33.48 KB
页数:2页
时间:2020-03-15
《生产者消费者程序代码.docx》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、生产者消费者代码importjava.util.concurrent.*;importjava.util.concurrent.locks.*;publicclassConsumerProducer{privatestaticBufferbuffer=newBuffer();publicstaticvoidmain(String[]args){//CreateathreadpoolwithtwothreadsExecutorServiceexecutor=Executors.newFixedThreadP
2、ool(2);executor.execute(newProducerTask());executor.execute(newConsumerTask());executor.shutdown();}//AtaskforaddinganinttothebufferprivatestaticclassProducerTaskimplementsRunnable{publicvoidrun(){try{inti=1;while(true){System.out.println("Producerwrites"
3、+i);buffer.write(i++);//Addavaluetothebuffer//PutthethreadintosleepThread.sleep((int)(Math.random()*10000));}}catch(InterruptedExceptionex){ex.printStackTrace();}}}//AtaskforreadinganddeletinganintfromthebufferprivatestaticclassConsumerTaskimplementsRunna
4、ble{publicvoidrun(){try{while(true){System.out.println("tttConsumerreads"+buffer.read());//PutthethreadintosleepThread.sleep((int)(Math.random()*10000));}}catch(InterruptedExceptionex){ex.printStackTrace();}}}//AninnerclassforbufferprivatestaticclassBu
5、ffer{privatestaticfinalintCAPACITY=1;//buffersizeprivatejava.util.LinkedListqueue=newjava.util.LinkedList();//CreateanewlockprivatestaticLocklock=newReentrantLock();//CreatetwoconditionsprivatestaticConditionnotEmpty=lock.newCondition();
6、privatestaticConditionnotFull=lock.newCondition();publicvoidwrite(intvalue){lock.lock();//Acquirethelocktry{while(queue.size()==CAPACITY){System.out.println("WaitfornotFullcondition");notFull.await();}queue.offer(value);notEmpty.signal();//SignalnotEmptyc
7、ondition}catch(InterruptedExceptionex){ex.printStackTrace();}finally{lock.unlock();//Releasethelock}}publicintread(){intvalue=0;lock.lock();//Acquirethelocktry{while(queue.isEmpty()){System.out.println("tttWaitfornotEmptycondition");notEmpty.await();}v
8、alue=queue.remove();notFull.signal();//SignalnotFullcondition}catch(InterruptedExceptionex){ex.printStackTrace();}finally{lock.unlock();//Releasethelockreturnvalue;}}}}
此文档下载收益归作者所有