Implementing Producer consumer pattern

后端 未结 3 1924
夕颜
夕颜 2021-01-06 16:29

I am trying to write a mail utility that places mails in a queue, and it is later consumed by a consumer thread.

I am trying to implement a typical producer-consumer

相关标签:
3条回答
  • 2021-01-06 16:57

    You are missing the shared queue. Without the queue, you have nothing.

    Producers put work onto the queue. Consumers take work off the queue. Use a BlockingQueue, whose put() and take() methods are blocking calls. Running producers and consumers in separate threads allows them to safely block while calling these methods.

    Neither the producers nor the consumers need to be Callable; Runnable will do. Using an Executor to tie it all together is a good idea.

    0 讨论(0)
  • 2021-01-06 17:00

    ExecutorService.submit schedules a Runnable or Callable for one execution. Your output shows that MailProducer and MailConsumer both executed once, so everything works like it should.

    You should place the inside of your Producer and Consumer methods in loops:

    import java.util.concurrent.*;
    
    public class Executor {
    
        private static final int NTHREADS = 25;
        private static final ExecutorService exec = 
            Executors.newFixedThreadPool(NTHREADS);
    
    
        public static void main(String[] args) {
            exec.submit(new MailConsumer());
            exec.submit(new MailProducer());
    
            System.out.println("inside main");  
        }
    
    
        static class MailProducer implements Runnable {
            @Override
            public void run() {
                while (true) {
                    System.out.println("inside mail Producer");
                    System.out.println("Thread executing = " +
                           Thread.currentThread().getName());
                }
           }
        }
    
        static class MailConsumer implements Runnable {
            @Override
            public void run() {
                while (true) {
                    System.out.println("inside mail Consumer");
                    System.out.println("Thread executing = " +
                           Thread.currentThread().getName());
                }
           }
        }
    }
    

    This gives the output you expect.

    0 讨论(0)
  • 2021-01-06 17:22
    1. You must use loops so that your producer/consumer code is executed more than once.

    2. Your threads do not communicate with each other. Currently you have only two threads being executed. Look at the example in the BlockingQueue javadoc of how to do it.

    0 讨论(0)
提交回复
热议问题