日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

分布与并行计算—生产者消费者模型队列(Java)

發布時間:2023/11/29 java 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 分布与并行计算—生产者消费者模型队列(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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。