分布与并行计算—生产者消费者模型实现(Java)
生活随笔
收集整理的這篇文章主要介紹了
分布与并行计算—生产者消费者模型实现(Java)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在實(shí)際的軟件開發(fā)過程中,經(jīng)常會(huì)碰到如下場(chǎng)景:某個(gè)模塊負(fù)責(zé)產(chǎn)生數(shù)據(jù),這些數(shù)據(jù)由另一個(gè)模塊來負(fù)責(zé)處理(此處的模塊是廣義的,可以是類、函數(shù)、線程、進(jìn)程等)。產(chǎn)生數(shù)據(jù)的模塊,就形象地稱為生產(chǎn)者;而處理數(shù)據(jù)的模塊,就稱為消費(fèi)者。
單單抽象出生產(chǎn)者和消費(fèi)者,還夠不上是生產(chǎn)者/消費(fèi)者模式。該模式還需要有一個(gè)緩沖區(qū)處于生產(chǎn)者和消費(fèi)者之間,作為一個(gè)中介。生產(chǎn)者把數(shù)據(jù)放入緩沖區(qū),而消費(fèi)者從緩沖區(qū)取出數(shù)據(jù)。
1、生產(chǎn)者
隨機(jī)生成一個(gè)大于20億的正整數(shù)
2、消費(fèi)者
判斷某個(gè)數(shù)字是否素?cái)?shù)(判斷素?cái)?shù)算法自己百度)
3、緩沖區(qū)
使用隊(duì)列(FIFO)
public class Consumer implements Runnable {BlockingQueue<Integer> blockingQueue;int n;CountDownLatch countDownLatch;public Consumer(BlockingQueue<Integer> blockingQueue, int n, CountDownLatch countDownLatch) {this.blockingQueue = blockingQueue;this.n = n;this.countDownLatch=countDownLatch;}@Overridepublic void run() {for(int i=0;i<n;i++){try {int cur=blockingQueue.take();isPrime(cur);/* System.out.println("消費(fèi)"+blockingQueue.size());*/} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("消費(fèi)者完成");countDownLatch.countDown();}int isPrime(int n){ //返回1表示判斷為質(zhì)數(shù),0為非質(zhì)數(shù),在此沒有進(jìn)行輸入異常檢測(cè)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 Producer implements Runnable{BlockingQueue<Integer> blockingQueue;int n;CountDownLatch countDownLatch;public Producer(BlockingQueue<Integer> blockingQueue, int n,CountDownLatch countDownLatch) {this.blockingQueue = blockingQueue;this.n = n;this.countDownLatch=countDownLatch;}@Overridepublic void run() {Random ra =new Random();for(int i=0;i<n;i++){try {blockingQueue.put(ra.nextInt(2000000000)+1);/* System.out.println("生產(chǎn)"+blockingQueue.size());*/} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("生產(chǎn)者完成");countDownLatch.countDown();} }總結(jié)
以上是生活随笔為你收集整理的分布与并行计算—生产者消费者模型实现(Java)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 女人梦到小孩子哭是什么意思
- 下一篇: 分布与并行计算—生产者消费者模型队列(J