在實際的軟件開發過程中,經常會碰到如下場景:某個模塊負責產生數據,這些數據由另一個模塊來負責處理(此處的模塊是廣義的,可以是類、函數、線程、進程等)。產生數據的模塊,就形象地稱為生產者;而處理數據的模塊,就稱為消費者。
單單抽象出生產者和消費者,還夠不上是生產者/消費者模式。該模式還需要有一個緩沖區處于生產者和消費者之間,作為一個中介。生產者把數據放入緩沖區,而消費者從緩沖區取出數據。
1、生產者
隨機生成一個大于20億的正整數
2、消費者
判斷某個數字是否素數(判斷素數算法自己百度)
3、緩沖區
使用隊列(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("消費"+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 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("生產"+blockingQueue.size());*/} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("生產者完成");countDownLatch.countDown();}
}