分布与并行计算—生产者消费者模型队列(Java)
生活随笔
收集整理的這篇文章主要介紹了
分布与并行计算—生产者消费者模型队列(Java)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在生產者-消費者模型中,在原有代碼基礎上,把隊列獨立為1個類實現,通過公布接口,由生產者和消費者調用。
public class Consumer implements Runnable {int n;CountDownLatch countDownLatch;public Consumer(BlockingQueue<Integer> blockingQueue, int n, CountDownLatch countDownLatch) {this.n = n;this.countDownLatch=countDownLatch;}@Overridepublic void run() {for(int i=0;i<n;i++){try {int cur=PACqueue.consume();/*System.out.println(this.toString()+i+"處理"+cur);*/isPrime(cur);/* System.out.println("消費"+blockingQueue.size());*/} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("消費者完成");countDownLatch.countDown();}int isPrime(int n){ //返回1表示判斷為質數,0為非質數,在此沒有進行輸入異常檢測double n_sqrt;if(n==2 || n==3) return 1;if(n%6!=1 && n%6!=5) return 0;n_sqrt=Math.floor(Math.sqrt((float)n));for(int i=5;i<=n_sqrt;i+=6){if(n%(i)==0 | n%(i+2)==0) return 0;}return 1;}} public class Model {public static void excute(int producerNum,int consumerNum,int num,CountDownLatch countDownLatch){BlockingQueue<Integer> blockingQueue=new LinkedBlockingQueue<>(num);for(int i=0;i<producerNum;i++){new Thread(new Producer(blockingQueue,num/producerNum,countDownLatch)).start();}for(int i=0;i<consumerNum;i++){new Thread(new Consumer(blockingQueue,num/consumerNum,countDownLatch)).start();}}public static void main(String[] args) {CountDownLatch countDownLatch=new CountDownLatch(6);long s=System.currentTimeMillis();excute(2,4,1000000,countDownLatch);try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}System.out.println((double) (System.currentTimeMillis()-s)/1000);} } public class PACqueue {//Java 阻塞隊列在隊列為空時,獲取元素的線程會等待隊列變為非空。當隊列滿時,存儲元素的線程會等待隊列可用。private static BlockingQueue<Integer> blockingQueue=new LinkedBlockingQueue<>(1000000);public static void produce (int n)throws InterruptedException{blockingQueue.put(n);}public static int consume ()throws InterruptedException{return blockingQueue.take();}} public class Producer implements Runnable{int n;CountDownLatch countDownLatch;public Producer(BlockingQueue<Integer> blockingQueue, int n,CountDownLatch countDownLatch) {this.n = n;this.countDownLatch=countDownLatch;}@Overridepublic void run() {Random ra =new Random();for(int i=0;i<n;i++){try {/* System.out.println(this.toString()+i+"生產");*/PACqueue.produce(ra.nextInt(2000000000)+1);/* System.out.println("生產"+blockingQueue.size());*/} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("生產者完成");countDownLatch.countDown();} } 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的分布与并行计算—生产者消费者模型队列(Java)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 孕妇梦到自己画画是什么意思
- 下一篇: 梦到陌生男人上我的床什么意思