项目中我们有时会遇到这样一种场景,首页中加载数据要弹出一个加载对话框,之后会弹出一个定位城市的选择确认框,或者个人喜好设置,或者感兴趣的栏目订阅选择对话框。为了便于管理dialog,取消前一个对话框后再显示下一个对话框,我们可以用FIFO队列对dialog进行排队。
private Queque < Dialog > dialogQueue = new LinkedList <>();private Dialog currentDialog = null ; // 当前显示的对话框private void showDialog ( Dialog dialog ) {if ( dialog != null ) {dialogQueue . offer ( dialog );}if ( currentDialog == null ) {currentDialog = dialogQueue . poll ();if ( currentDialog != null ) {currentDialog . show ();currentDialog . setOnDismissListener ( new DialogInterface . OnDismissListener () {@Overridepublic void onDismiss ( DialogInterface dialog ) {currentDialog = null ;showDialog ( null );}});}}}
OK,这样只需要在我们需要显示对话框的时候调用showDialog()方法就可以了,是不是很方便呢~~
Java中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列。Queue接口与List、Set接口同一级别,都是继承了Collection接口,LinkedList实现了Queue接口。队列有两个基本操作:在队列尾部加入一个元素,和从队列头部移动一个元素。也就是说,队列以一种先进先出的方式管理数据,如果你试图向一个已经满了的阻塞队列中添加一个元素或者从一个空的阻塞队列中移除一个元素,将导致线程阻塞。
Queue使用时要尽量避免Collection接口的add()和remove()方法。最好入队使用 offer() ,出队使用poll() ,不会抛出异常。
add
增加一个元索
如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素
如果队列为空,则抛出一个NoSuchElementException异常
remove 移除并返回队列头部的元素
offer 添加一个元素并返回true
如果队列已满,则返回false
poll
移除并返问队列头部的元素
如果队列为空,则返回null
poll
/**
* Inserts the specified element into this queue if it is possible to do
* so immediately without violating capacity restrictions.
* When using a capacity-restricted queue, this method is generally
* preferable to {@link #add}, which can fail to insert an element only
* by throwing an exception.
*
* @param e the element to add
* @return <tt>true</tt> if the element was added to this queue, else
* <tt>false</tt>
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null and
* this queue does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this queue
*/
boolean offer(E e);
/**
* Retrieves and removes the head of this queue,
* or returns <tt>null</tt> if this queue is empty.
*
* @return the head of this queue, or <tt>null</tt> if this queue is empty
*/
E poll();