使用队列的生产者/使用者线程我想创造一些Producer/Consumer线程应用程序。但我不知道在两者之间实现队列的最佳方式是什么。所以我有两个想法(这两个想法都可能是完全错误的)。我想知道哪一个更好,如果两者都很糟糕,那么实现队列的最佳方法是什么。我关心的主要是这些例子中队列的实现。我正在扩展一个队列类,它是一个内部类,并且是线程安全的。下面是两个例子,每个例子有4个类。主修班-public class SomeApp{
private Consumer consumer;
private Producer producer;
public static void main (String args[])
{
consumer = new Consumer();
producer = new Producer();
}}消费者阶层-public class Consumer implements Runnable{
public Consumer()
{
Thread consumer = new Thread(this);
consumer.start();
}
public void run()
{
while(true)
{
//get an object off the queue
Object object = QueueHandler.dequeue();
//do some stuff with the object
}
}}制片人班-public class Producer implements Runnable{
public Producer()
{
Thread producer = new Thread(this);
producer.start();
}
public void run()
{
while(true)
{
//add to the queue some sort of unique object
QueueHandler.enqueue(new Object());
}
}}排队类-public class QueueHandler{
//This Queue class is a thread safe (written in house) class
public static Queue<Object> readQ = new Queue<Object>(100);
public static void enqueue(Object object)
{
//do some stuff
readQ.add(object);
}
public static Object dequeue()
{
//do some stuff
return readQ.get();
}}或主修班-public class SomeApp{
Queue<Object> readQ;
private Consumer consumer;
private Producer producer;
public static void main (String args[])
{
readQ = new Queue<Object>(100);
consumer = new Consumer(readQ);
producer = new Producer(readQ);
}}
3 回答
UYOU
TA贡献1878条经验 获得超4个赞
把你所有的制片人放在一起 把你所有的消费者都放在另一个 ExecutorService
;如果有必要,使用
final ExecutorService producers = Executors.newFixedThreadPool(100);final ExecutorService consumers = Executors.newFixedThreadPool(100);while (/* has more work */) { producers.submit(...);}producers.shutdown();producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);consumers.shutdown();consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
producers
consumers
.
幕布斯7119047
TA贡献1794条经验 获得超8个赞
添加回答
举报
0/150
提交
取消