我能找到的官方文檔和論壇帖子對此很模糊。他們說這取決於程序員決定在中斷還是退出後繼續執行,但我找不到任何可以保證一個或另一個條件的文檔。線程和中斷:繼續還是退出?
這裏是有問題的代碼:
private final LinkedBlockingQueue<Message> messageQueue = new LinkedBlockingQueue<Message>();
// The sender argument is an enum describing who sent the message: the user, the app, or the person on the other end.
public void sendMessage(String address, String message, Sender sender) {
messageQueue.offer(Message.create(address, message, sender));
startSenderThread();
}
private Thread senderThread;
private void startSenderThread(){
if(senderThread == null || !senderThread.isAlive()){
senderThread = new Thread(){
@Override
public void run() {
loopSendMessage();
}
};
senderThread.start();
}
}
private void loopSendMessage(){
Message queuedMessage;
// Should this condition simply be `true` instead?
while(!Thread.interrupted()){
try {
queuedMessage = messageQueue.poll(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
EasyLog.e(this, "SenderThread interrupted while polling.", e);
continue;
}
if(queuedMessage != null)
sendOrQueueMessage(queuedMessage);
else
break;
}
}
// Queue in this context means storing the message in the database
// so it can be sent later.
private void sendOrQueueMessage(Message message){
//Irrelevant code omitted.
}
的sendMessage()
方法可以從任何線程和在任何時間被調用。它會發送一條新消息發送到消息隊列,並在發送方線程未運行時啓動它。發送者線程用超時輪詢隊列,並處理消息。如果隊列中沒有更多消息,則線程退出。
這是一個Android應用程序,可以自動執行短信處理。這是在一個處理出站消息的類中,決定是立即發送還是保存它們以後發送,因爲Android有一個內部100個消息/小時的限制,只能通過生根和訪問設置數據庫來改變。
消息可以從應用程序的不同部分同時發送,由用戶或應用程序本身發送。確定何時排隊等待以後需要同步處理以避免需要原子消息計數。
我想優雅地處理中斷,但我不想停止發送消息,如果有更多的發送。關於線程的Java文檔說大多數方法在被中斷後簡單地返回,但是這會將未發送的消息留在隊列中。
任何人都可以請推薦一個行動方案嗎?
我的印象是,中斷不總是程序員控制的,我必須處理來自系統的中斷,因爲在其他地方需要操作系統線程。這不正確嗎? –
我不認爲OS上下文切換會拋出中斷,所以你不必擔心這一點。這個SO問題涵蓋了它比我可以解釋更好:http://stackoverflow.com/questions/2126997/who-is-calling-the-java-thread-interrupt-method-if-im-not – dkatzel
所以唯一一次我如果我自己調用interrupt()或將線程傳遞給調用它的另一個方法,可以得到中斷嗎? –