生产者消费者使用线程

时间:2013-10-31 01:39:27

标签: java multithreading consumer producer

我正在编写一个使用多线程概念在Java中实现Producer Consumer问题的程序。以下是我应该如何做的一些细节:

1)主线程应创建一个缓冲区,其容量指定为命令行参数。生产者和消费者线程的数量也被指定为命令行参数。我应该为每个生产者和消费者线程分配一个唯一的号码。如何为生产者和消费者线程分配唯一编号?

2)生产者线程在无限循环中运行。它生成一个具有以下格式的数据项(字符串):<producer number>_<data item number>。例如,来自线程编号1的第一个数据项将是1_1,而来自线程编号3的第二个数据项将是3_2。如何以这种格式创建数据项?

3)然后,Producer线程将一个条目写入生产者日志文件(&lt; producer number&gt;“Generated”<data item>)。在写入日志条目时,它会尝试插入缓冲区。如果插入成功,则会在日志文件中创建一个条目(<producer number> <data item>“插入成功”)。我该如何编写这样的代码?

下面是我编写的Java代码。

import java.util.*;
import java.util.logging.*;

public class PC2
{
    public static void main(String args[])
    {
            ArrayList<Integer> queue = new ArrayList<Integer>();

            int size = Integer.parseInt(args[2]);
            Thread[] prod = new Thread[Integer.parseInt(args[0])];
            Thread[] cons = new Thread[Integer.parseInt(args[1])];

            for(int i=0; i<prod.length; i++)
            {
                    prod[i] = new Thread(new Producer(queue, size));
                    prod[i].start();
            }

            for(int i=0; i<cons.length; i++)
            {
                    cons[i] = new Thread(new Consumer(queue, size));
                    cons[i].start();
                }

    }
}

class Producer extends Thread
{
    private final ArrayList<Integer> queue;
    private final int size;

    public Producer(ArrayList<Integer> queue, int size)
    {
            this.queue = queue;
            this.size = size;
    }

    public void run()
    {
            while(true){
            for(int i=0; i<size; i++)
            {
                    System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId());
try
                    {
                            produce(i);
                            Thread.sleep(3000);
                    }
                    catch(Exception e)
                    {
                            Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e);
                    }
            }}
    }


    public void produce(int i) throws InterruptedException
    {
            while(queue.size() == size)
            {
                    synchronized(queue)
                    {
                            System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size());
                            queue.wait();
                       }
            }
            synchronized(queue)
            {
                    queue.add(i);
                    queue.notifyAll();
            }
    }
}

class Consumer extends Thread
{
    private final ArrayList<Integer> queue;
    private final int size;

    public Consumer(ArrayList<Integer> queue, int size)
    {
            this.queue = queue;
            this.size = size;
    }

    public void run()
    {
            while(true)
            {
                    try
                    {       System.out.println("Consumed: "+consume());
                            Thread.sleep(1000);
                    }
                    catch(Exception e)
                    {
                            Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e);
                    }
            }
    }

    public int consume() throws InterruptedException
    {
            while(queue.isEmpty())
            {
                    synchronized(queue)
                    {
                            System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size());
                            queue.wait();
                        }
            }

            synchronized (queue)
            {
                    queue.notifyAll();
                    System.out.println("Consumed by id "+Thread.currentThread().getId());
                    return (Integer) queue.remove(0);

            }
    }
}

如何执行上述步骤?

5 个答案:

答案 0 :(得分:1)

  

我应该为每个生产者和消费者分配一个唯一的号码   线。如何为生产者和消费者分配唯一编号   线程?

将实例(非静态)变量添加到Producer / Consumer类。初始化新的生产者/消费者对象时,请传入唯一编号。您可以使用主班中的int counter跟踪您的号码。

  

2)生产者线程在无限循环中运行。它产生了一个   具有以下格式的数据项(字符串):&lt;生产者编号&gt; _&lt;   数据项目编号&gt; 。例如,来自线程编号的第一个数据项   1将是1_1并且来自第3号线的第二数据项将是3_2。   如何以这种格式创建数据项?

使用同步方法和/或原子变量。查看Java Concurrency

  

3)然后,Producer线程将一个条目写入生产者日志文件   (&lt; producer number&gt;“Generated”&lt; data item&gt;)。写日志后   条目,它试图插入缓冲区。如果是插入   成功后,它会在日志文件中创建一个条目(&lt; producer number&gt;   &LT;数据项&gt; “插入成功”)。我该如何编写这样的代码?

我的回答与上一个问题相同:阅读Java并发性。花一小时阅读有关同步,锁和原子变量的内容,我保证您可以轻松编写程序。

答案 1 :(得分:1)

对于生产者消费者问题,最佳解决方案是BlockingQueue。我正在测试一些如此设计的相同类型的程序,现在根据您的需要修改它。

看看它是否有帮助。

import java.util.concurrent.*;
public class ThreadingExample {

    public static void main(String args[]){
        BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<Message>(100);
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(new Producer(blockingQueue));
        exec.execute(new Consumer(blockingQueue));
    }

}
class Message{
    private static int count=0;
    int messageId;
    Message(){
        this.messageId=count++;
        System.out.print("message Id"+messageId+" Created ");
    }
}
class Producer implements Runnable{

    private BlockingQueue<Message> blockingQueue;
    Producer(BlockingQueue<Message> blockingQueue){
        this.blockingQueue=blockingQueue;
    }

    @Override
    public void run(){
        while(!Thread.interrupted()){
            System.out.print("Producer Started");
            try {
                blockingQueue.put(new Message());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Producer Done");
        }
    }
}

class Consumer implements Runnable{
    private BlockingQueue<Message> blockingQueue;
    Consumer(BlockingQueue<Message> blockingQueue){
        this.blockingQueue=blockingQueue;
    }

    @Override
    public void run(){
        while(!Thread.interrupted()){
            System.out.print("Concumer Started");
            try{
                Message message  = blockingQueue.take();
                System.out.print("message Id"+message.messageId+" Consumed ");
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("Concumer Done");
        }
    }
}

答案 2 :(得分:0)

我尝试了以下可能适合您的方法,除了3上的缓冲条件,您可以自己添加部分代码。 希望这会有所帮助。

public class Message {

    private String msg;

    public Message(String msg) {
        super();
        this.msg = msg;
    }

    public String getMsg(){
        return msg;
    }
}




import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {

    private BlockingQueue<Message> queue;
    private boolean run = true;

    public Producer(BlockingQueue<Message> queue) {
        super();
        this.queue = queue;
    }

    public void setRun(boolean val) {
        this.run = val;
    }

    @Override
    public void run() {
        int i = 0;
        while (run) {
            Message msg = new Message(Thread.currentThread().getName() + "_"+ i);
            try {
                Thread.sleep(i * 100);
                queue.put(msg);
                System.out.println("Producer: "+Thread.currentThread().getName()+" produced and added to the queue: "+msg.getMsg());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i++;
            if(i==10){
                setRun(false);
                System.out.println(Thread.currentThread().getName()+" stopped");
            }
        }

    }
}



import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable{

    private BlockingQueue<Message> queue;
    private boolean run = true;

    public Consumer(BlockingQueue<Message> queue) {
        super();
        this.queue = queue;
    }

    public void setRun(boolean val){
        this.run = val;
    }

    @Override
    public void run() {
        while(run){
            try {
                Thread.sleep(100);
                Message msg = queue.take();
                System.out.println("Consumer: "+Thread.currentThread().getName()+"         generated/consumed "+msg.getMsg());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
  }




import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumerMain {

    public static void main(String[] args) {
        System.out
                .println("please enter the number of producer:consumer:size of the queue in order");

        Scanner scan = new Scanner(System.in);

        Thread[] prodThreads = new Thread[scan.nextInt()];
        Thread[] consThreads = new Thread[scan.nextInt()];
        BlockingQueue<Message> queue = new ArrayBlockingQueue<Message>(scan.nextInt());

        for (int i = 0; i < prodThreads.length; i++) {
            prodThreads[i] = new Thread(new Producer(queue), "" + i);
            prodThreads[i].start();
        }

        for (int i = 0; i < consThreads.length; i++) {
            consThreads[i] = new Thread(new Consumer(queue), "" + i);
            consThreads[i].start();
        }


    }

}

答案 3 :(得分:0)

请参阅以下代码。您可以根据命令行参数更改常量值。我已经测试了代码,它的工作符合您的要求。

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumerProblem {
    public static int CAPACITY = 10; // At a time maximum of 10 tasks can be
                                        // produced.
    public static int PRODUCERS = 2;
    public static int CONSUMERS = 4;

    public static void main(String args[]) {
        Queue<String> mTasks = new LinkedList<String>();
        for (int i = 1; i <= PRODUCERS; i++) {
            Thread producer = new Thread(new Producer(mTasks));
            producer.setName("Producer " + i);
            producer.start();
        }
        for (int i = 1; i <= CONSUMERS; i++) {
            Thread consumer = new Thread(new Consumer(mTasks));
            consumer.setName("Consumer " + i);
            consumer.start();
        }

    }

}

class Producer implements Runnable {

    Queue<String> mSharedTasks;
    int taskCount = 1;

    public Producer(Queue<String> mSharedTasks) {
        super();
        this.mSharedTasks = mSharedTasks;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (mSharedTasks) {
                try {
                    if (mSharedTasks.size() == ProducerConsumerProblem.CAPACITY) {
                        System.out.println("Producer Waiting!!");
                        mSharedTasks.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            while (mSharedTasks.size() != ProducerConsumerProblem.CAPACITY) {

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                }

                String produceHere = Thread.currentThread().getName()
                        + "_Item number_" + taskCount++;

                synchronized (mSharedTasks) {
                    mSharedTasks.add(produceHere);
                    System.out.println(produceHere);
                    if (mSharedTasks.size() == 1) {
                        mSharedTasks.notifyAll(); // Informs consumer that there
                                                    // is something to consume.
                    }
                }
            }

        }
    }
}

class Consumer implements Runnable {
    Queue<String> mSharedTasks;

    public Consumer(Queue<String> mSharedTasks) {
        super();
        this.mSharedTasks = mSharedTasks;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (mSharedTasks) {
                if (mSharedTasks.isEmpty()) { // Checks whether there is no task
                                                // to consume.
                    try {
                        mSharedTasks.wait(); // Waits for producer to produce!
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
            while (!mSharedTasks.isEmpty()) { // Consumes till task list is
                                                // empty
                try {
                    // Consumer consumes late hence producer has to wait...!
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                synchronized (mSharedTasks) {

                    System.out.println(Thread.currentThread().getName()
                            + " consumed " + mSharedTasks.poll());
                    if (mSharedTasks.size() == ProducerConsumerProblem.CAPACITY - 1)
                        mSharedTasks.notifyAll();
                }

            }

        }
    }

}

答案 4 :(得分:-1)

//If it happens that you will have a formatted string like "August 3, 2015 3:00 pm"
//It's is better to separate the 'AM/PM' format via `tt` formatter.
DateTime now = DateTime.Now;
string formatted1 = now.ToString("MMMM dd, yyyy hh:mm ") + now.ToString("tt").ToLower();
Console.WriteLine(formatted1);

string formatted2 = now.ToString("MM/dd/yyyy hh:mm ") + now.ToString("tt").ToLower();
Console.WriteLine(formatted2);
Console.ReadLine();