宁夏建设网站公司,网页游戏大全4399,二级域名注册平台,滁州网站建设哪个好点在实际的软件开发过程中#xff0c;经常会碰到如下场景#xff1a;某个模块负责产生数据#xff0c;这些数据由另一个模块来负责处理#xff08;此处的模块是广义的#xff0c;可以是类、函数、线程、进程等#xff09;。产生数据的模块#xff0c;就形象地称为生产者经常会碰到如下场景某个模块负责产生数据这些数据由另一个模块来负责处理此处的模块是广义的可以是类、函数、线程、进程等。产生数据的模块就形象地称为生产者而处理数据的模块就称为消费者。
单单抽象出生产者和消费者还够不上是生产者消费者模式。该模式还需要有一个缓冲区处于生产者和消费者之间作为一个中介。生产者把数据放入缓冲区而消费者从缓冲区取出数据。 1、生产者
随机生成一个大于20亿的正整数
2、消费者
判断某个数字是否素数判断素数算法自己百度
3、缓冲区
使用队列FIFO
public class Consumer implements Runnable {BlockingQueueInteger blockingQueue;int n;CountDownLatch countDownLatch;public Consumer(BlockingQueueInteger blockingQueue, int n, CountDownLatch countDownLatch) {this.blockingQueue blockingQueue;this.n n;this.countDownLatchcountDownLatch;}Overridepublic void run() {for(int i0;in;i){try {int curblockingQueue.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(n2 || n3) return 1;if(n%6!1 n%6!5) return 0;n_sqrtMath.floor(Math.sqrt((float)n));for(int i5;in_sqrt;i6){if(n%(i)0 | n%(i2)0) return 0;}return 1;}}
public class Model {public static void excute(int producerNum,int consumerNum,int num,CountDownLatch countDownLatch){BlockingQueueInteger blockingQueuenew LinkedBlockingQueue(num);for(int i0;iproducerNum;i){new Thread(new Producer(blockingQueue,num/producerNum,countDownLatch)).start();}for(int i0;iconsumerNum;i){new Thread(new Consumer(blockingQueue,num/consumerNum,countDownLatch)).start();}}public static void main(String[] args) {CountDownLatch countDownLatchnew CountDownLatch(6);long sSystem.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{BlockingQueueInteger blockingQueue;int n;CountDownLatch countDownLatch;public Producer(BlockingQueueInteger blockingQueue, int n,CountDownLatch countDownLatch) {this.blockingQueue blockingQueue;this.n n;this.countDownLatchcountDownLatch;}Overridepublic void run() {Random ra new Random();for(int i0;in;i){try {blockingQueue.put(ra.nextInt(2000000000)1);/* System.out.println(生产blockingQueue.size());*/} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(生产者完成);countDownLatch.countDown();}
}