我现在想做一个消息队列,一边在不停的放数据,一边在不停的take,怎么保证这个take一直在执行?,是不是要写一个死循环的?还是有别的什么方式?
迷茫2017-04-17 17:53:32
Assume you are in stand-alone mode
while(true){
object obj = queue.take();//这里会阻塞的
//去做别的处理
}
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;
}
}