【核心研究】訊息佇列_MessageQueue,隊列_messagequeue

來源:互聯網
上載者:User

【核心研究】訊息佇列_MessageQueue,隊列_messagequeue

訊息佇列採用排隊方式對訊息進行處理,即先到的訊息會先得到處理,但如果訊息本身指定了被處理的時刻,則必須等到該時刻才能處理該訊息。訊息在MessageQueue中使用Message類表示,隊列中的訊息以鏈表的結構進行儲存,Message對象內部包含一個next變數,該變數指向下一個訊息對象。

MessageQueue中的兩個主要函數是“取出訊息”和“添加訊息”,分別是next()和enquenceMessage()。


next()函數

final Message next() {        int pendingIdleHandlerCount = -1; // -1 only during first iteration        int nextPollTimeoutMillis = 0;        for (;;) {            if (nextPollTimeoutMillis != 0) {                Binder.flushPendingCommands();            }            nativePollOnce(mPtr, nextPollTimeoutMillis);            synchronized (this) {                // Try to retrieve the next message.  Return if found.                final long now = SystemClock.uptimeMillis();                final Message msg = mMessages;                if (msg != null) {                    final long when = msg.when;                    if (now >= when) {                        mBlocked = false;                        mMessages = msg.next;                        msg.next = null;                        if (Config.LOGV) Log.v("MessageQueue", "Returning message: " + msg);                        return msg;                    } else {                        nextPollTimeoutMillis = (int) Math.min(when - now, Integer.MAX_VALUE);                    }                } else {                    nextPollTimeoutMillis = -1;                }                // If first time, then get the number of idlers to run.                if (pendingIdleHandlerCount < 0) {                    pendingIdleHandlerCount = mIdleHandlers.size();                }                if (pendingIdleHandlerCount == 0) {                    // No idle handlers to run.  Loop and wait some more.                    mBlocked = true;                    continue;                }                if (mPendingIdleHandlers == null) {                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];                }                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);            }            // Run the idle handlers.            // We only ever reach this code block during the first iteration.            for (int i = 0; i < pendingIdleHandlerCount; i++) {                final IdleHandler idler = mPendingIdleHandlers[i];                mPendingIdleHandlers[i] = null; // release the reference to the handler                boolean keep = false;                try {                    keep = idler.queueIdle();                } catch (Throwable t) {                    Log.wtf("MessageQueue", "IdleHandler threw exception", t);                }                if (!keep) {                    synchronized (this) {                        mIdleHandlers.remove(idler);                    }                }            }            // Reset the idle handler count to 0 so we do not run them again.            pendingIdleHandlerCount = 0;            // While calling an idle handler, a new message could have been delivered            // so go back and look again for a pending message without waiting.            nextPollTimeoutMillis = 0;        }    }

該函數的內部流程分三步:

1. 調用nativePollOnce(mPtr, int time)。這是一個JNI函數,作用是從訊息佇列中取出一個訊息。MessageQueue類內部本身並沒有儲存訊息佇列,真正的訊息佇列資料儲存在JNI中的C代碼中,在C環境中建立了一個NativeMessageQueue資料對象,這就是nativePollOnce()第一個參數的意義。它是一個int型變數,在C環境中,該變數被強制轉換為一個NativeMessageQueue對象。在C環境中,如果訊息佇列中沒有訊息,將導致當前線程被掛起(wait),如果訊息佇列中有訊息,則C代碼中將把該訊息賦值給Java環境中的mMessages變數。

2. 接下來的代碼被包含在synchronized(this)中,this被用作取訊息和寫訊息的鎖。僅僅是判斷訊息所指定的執行時間是否到了。如果到了,就返回該訊息,並將mMessages變數置空;如果時間還沒有到,則嘗試讀取下一個訊息。

3. 如果mMessages為空白,則說明C環境中的訊息佇列沒有可執行檔訊息了,因此,執行mPendingIdleHanlder列表中的“空閑回呼函數”。可以向MessageQueue中註冊一些“空閑回呼函數”,從而當線程中沒有訊息可處理的時候去執行這些“空閑代碼”。


enquenceMessage()函數

final boolean enqueueMessage(Message msg, long when) {        if (msg.when != 0) {            throw new AndroidRuntimeException(msg                    + " This message is already in use.");        }        if (msg.target == null && !mQuitAllowed) {            throw new RuntimeException("Main thread not allowed to quit");        }        final boolean needWake;        synchronized (this) {            if (mQuiting) {                RuntimeException e = new RuntimeException(                    msg.target + " sending message to a Handler on a dead thread");                Log.w("MessageQueue", e.getMessage(), e);                return false;            } else if (msg.target == null) {                mQuiting = true;            }            msg.when = when;            //Log.d("MessageQueue", "Enqueing: " + msg);            Message p = mMessages;            if (p == null || when == 0 || when < p.when) {                msg.next = p;                mMessages = msg;                needWake = mBlocked; // new head, might need to wake up            } else {                Message prev = null;                while (p != null && p.when <= when) {                    prev = p;                    p = p.next;                }                msg.next = prev.next;                prev.next = msg;                needWake = false; // still waiting on head, no need to wake up            }        }        if (needWake) {            nativeWake(mPtr);        }        return true;    }
該函數內部分為兩步:

1. 將參數msg賦值給mMessages。

2. 調用nativeWake(mPtr)。這是一個JNI函數,其內部會將mMessages訊息添加到C環境中的訊息佇列中,並且如果訊息線程正處於掛起(wait)狀態,則喚醒該線程。


win7系統的Windows功可以裡沒有訊息佇列(Microsoft Message Queue (MSMQ)伺服器)的選項

你好,WIN7裡有這一項的。個體步驟如下:
開始一控制台一程式一點擊右邊“程式和功能”下邊的“啟動和關閉WINDOWS功能”
這樣你就那看到Microsoft Message Queue (MSMQ)伺服器那個選項的。勾上就OK了。。

希望我的回答能對你有所協助!!
 
C# 對於訊息佇列的操作怎刪除訊息佇列中的訊息?

System.Messaging.Message[] messages = queue.GetAllMessages();

foreach (System.Messaging.Message message in messages)

{

//Do something with the message.

}

你也可以用GetMessageEnumerator2方法代替上面的MessageQueue.GetAllMessages方法。雖然這兩個方 法的用法類似,但GetMessageEnumerator2隻能向前(forward-only)。對於非常龐大的隊列,則應用使用這個方法,而不是 MessageQueue.GetAllMessages方法。

這是因為GetAllMessages方法領取所有訊息,把它們儲存在當地記憶體中;而GetMessageEnumerator2方法只領取當前訊息在本地儲存,在調用MoveNext時才領取下一條訊息。下面這條語句舉例說明了GetMessageEnumerator2方法的用法。這段代碼檢查隊列中的每一條訊息,再刪除它。

MessageEnumerator enumerator = queue.GetMessageEnumerator2();
while (enumerator.MoveNext())

enumerator.RemoveCurrent();
不過沒有你想要的想刪哪條就刪哪條的那個用法似乎。。。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.