网站底部特效,把网站做成app,制作小程序网站源码,如何设计网站的链接在生产者-消费者模型中#xff0c;在原有代码基础上#xff0c;把队列独立为1个类实现#xff0c;通过公布接口#xff0c;由生产者和消费者调用。
public class Consumer implements Runnable {int n;CountDownLatch countDownLatch;public Consumer(BlockingQueueIn…在生产者-消费者模型中在原有代码基础上把队列独立为1个类实现通过公布接口由生产者和消费者调用。
public class Consumer implements Runnable {int n;CountDownLatch countDownLatch;public Consumer(BlockingQueueInteger blockingQueue, int n, CountDownLatch countDownLatch) {this.n n;this.countDownLatchcountDownLatch;}Overridepublic void run() {for(int i0;in;i){try {int curPACqueue.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(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 PACqueue {//Java 阻塞队列在队列为空时获取元素的线程会等待队列变为非空。当队列满时存储元素的线程会等待队列可用。private static BlockingQueueInteger blockingQueuenew 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(BlockingQueueInteger blockingQueue, int n,CountDownLatch countDownLatch) {this.n n;this.countDownLatchcountDownLatch;}Overridepublic void run() {Random ra new Random();for(int i0;in;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();}
}