在生产者-消费者模型中,在原有代码基础上,把队列独立为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;
}
@Override
public 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;
}
@Override
public 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();
}
}