search

Home  >  Q&A  >  body text

消息队列 - java里面实现MQ的原理是什么?

我现在想做一个消息队列,一边在不停的放数据,一边在不停的take,怎么保证这个take一直在执行?,是不是要写一个死循环的?还是有别的什么方式?

大家讲道理大家讲道理2890 days ago530

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 17:53:32

    It’s done, I’ve written an infinite loop, thank you all.

    reply
    0
  • 迷茫

    迷茫2017-04-17 17:53:32

    Assume you are in stand-alone mode

    while(true){

    object obj = queue.take();//这里会阻塞的
    //去做别的处理

    }

    reply
    0
  • PHPz

    PHPz2017-04-17 17:53:32

    Generally, the release and collection of data correspond to two threads or processes to achieve asynchronous purposes and maximize throughput. So what you said is right, one keeps adding data and one keeps getting data, but there is a problem. If you add data too slowly or too fast, or the data is processed too slowly or too fast, it will happen. The queue is empty or the queue is full. Once this situation occurs, it means that one party has to wait for the other party to complete the action before continuing, which reduces the throughput, so there is usually a timeout return.
    The following one is a message queue get without timeout

    public Message receive() throws InterruptedException {
            
            synchronized (queue) {
                
                if(queue.isEmpty()){
                    queue.wait(1000);
                }
                if(queue.isEmpty()){
                    return null;//timeout
                }
                Message message=queue.get(0);
                queue.remove(0);
                return message;
            }
    
        }

    reply
    0
  • Cancelreply