java多生产者-多消费者问题(+高分哦!)
发布网友
发布时间:2022-04-30 03:35
我来回答
共1个回答
热心网友
时间:2022-04-10 00:02
生产者向阻塞队列中放入随即整数(可以为两个消费者提供不同的队列),消费者从队列中取出元素进行判断,可以用BlockingQueue实现同步,很方便,质数和平方数判断在写个静态方法即可~自己想想看,需要代码就说下
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Procer extends Thread
{
private List<BlockingQueue<Integer>> queueList;
public Procer(List<BlockingQueue<Integer>> bQueueList)
{
this.queueList = bQueueList;
}
public void run()
{
int count = 0;
while (count++ < 10)
{
int randomInt = (int) (Math.random() * 100 + 1);
try
{
for(BlockingQueue<Integer> queue:queueList)
{
queue.put(randomInt);
}
System.out.println(randomInt + " is put..");
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args)
{
BlockingQueue<Integer> bQueue = new LinkedBlockingQueue<Integer>();
BlockingQueue<Integer> bQueueCopy = new LinkedBlockingQueue<Integer>();
List<BlockingQueue<Integer>> list=new ArrayList<BlockingQueue<Integer>>();
list.add(bQueue);
list.add(bQueueCopy);
new Procer(list).start();
new Procer(list).start();
new Procer(list).start();
new PrimeConsumer(bQueue).start();
new SquareConsumer(bQueueCopy).start();
}
}
class PrimeConsumer extends Thread
{
private BlockingQueue queue;
public PrimeConsumer(BlockingQueue<Integer> bQueue)
{
this.queue = bQueue;
}
public void run()
{
do
{
try
{
int i = (Integer) queue.take();
if (CheckNumber.isPrime(i))
{
System.out.println(i + " is prime..");
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
while (queue.size() != 0);
}
}
class SquareConsumer extends Thread
{
private BlockingQueue queue;
public SquareConsumer(BlockingQueue<Integer> bQueue)
{
this.queue = bQueue;
}
public void run()
{
do
{
try
{
int i = (Integer) queue.take();
if (CheckNumber.isSquare(i))
{
System.out.println(i + " is square..");
}
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
while (queue.size() != 0);
}
}
class CheckNumber
{
public static boolean isPrime(int n)
{
if (n == 1)
return false;
for (int i = 2; i < n / 2 + 1; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
public static boolean isSquare(int n)
{
int l = (int) Math.sqrt(n);
for (int i = 1; i <= l; i++)
{
if (i * i == n)
{
return true;
}
}
return false;
}
}
都写在一个类里了,比较乱,测试正确~