2014-06-05 35 views
0

我有一個小問題。當onStartCommand()被觸發時,我有一個獲得SingleTon線程的服務。線程或Runnable如何立即被殺死

public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    Thread t = myThreadFactory.getConnectionThreadWhatever(); 
    if (t.isAlive() && !t.isinterrupted()) 
    { 
    // do actions when thread is already alive 
    } 
    else 
    { 
    // do actions to start and run the thread. e.g. t = new ConnectionThread().start(); 
    } 
} 

現在線程需要循環這就好比一個Runnable(僞!)

public static boolean isRunning = false; 
public void run() 
{ 
    isRunning = true; 
    while (isRunning) 
    { 
     // open the httpconnection with a (read)timeout of 300 (long polling, whatever) 
    } 
} 

現在我=我想盡快殺死線程作爲連接在網絡中廣播下降接收者或任何情況。

什麼是常見的方式瞬間殺死它沒有(例如300秒)發生超時之前等待?

目前,我在另一個類

public void stopThreadconnectionInstantlyWhatever() 
{ 
    ConnectionThread.isRunning = false; 
    Thread t = myFactory.getConnectionThread(); 
    t.interrupt(); 
} 

這樣做現在的問題似乎是,線可能會等到timout發生,但每一秒都是應該避免的更多電量。所以......任何想法? :-)

嗯,我能得到一個Singleton模式的HttpURLConnection的藏漢並殺死它超時出現之前,但是這僅僅是一個案件

+0

@EmanuelSeibold Thread.sleep()方法拋出一個InterruptedException,並且將停止在被中斷。在httpconnection的文檔中沒有地方處理線程的中斷? – Cruncher

+0

@EmanuelSeibold通常有一種優雅的做事方式。如果有什麼東西等待或阻塞很長一段時間,幾乎總是有某種方法可以在不終止線程的情況下將其喚醒。你按照個案處理這些事情。這是他們不贊成使用'Thread.stop()'的原因,因爲總有更好的方法。我們需要更多關於正在等待的細節,因爲這會改變如何喚醒它。 – Cruncher

+0

查看道格拉斯施密特的視頻:http://youtu.be/wpEeZUjTiS4?t=4m17s –

回答

1

嘗試讀取this article

實施取消在語言規範任務

沒有給出任何中斷特定語義,但是在較大的 程序,它是很難維持中斷 比其他取消任何語義。取決於活動,用戶可通過GUI或通過網絡機制(如 )請求取消爲JMX或Web服務。它也可以被程序邏輯請求。 例如,如果Web爬網程序檢測到磁盤已滿,或者並行算法可能會啓動多個線程來搜索解決方案空間的不同區域,並且一旦其中一個解決方案空間發現解決方案,則可以自動關閉它。 。

僅僅因爲一個任務是 取消並不意味着它需要立即中斷請求 迴應。對於在循環中執行代碼的任務,通常每個循環迭代只檢查一次中斷 。根據 循環需要執行的時間長度,在 任務代碼發現線程已被中斷(通過輪詢 中斷的狀態爲Thread.isInterrupted()或通過調用 阻止方法)之前可能需要一些時間。如果任務需要更響應,則可以更頻繁地輪詢 中斷狀態。攔截方法通常輪詢 立即進入中斷狀態,拋出 InterruptedException如果它被設置爲提高響應能力。

的一個 時間是可以接受的吞中斷是當你知道 線程即將退出。這種情況僅在調用可中斷方法的類 是Thread的一部分而不是Runnable 或通用庫代碼時發生,如清單5所示。它的 創建一個枚舉素數直到中斷的線程 和允許線程在中斷時退出。尋求素數的 循環會檢查兩處中斷:一次是在while循環的頭部輪詢 isInterrupted()方法,一旦 調用阻塞BlockingQueue.put()方法。

public class PrimeProducer extends Thread { 
private final BlockingQueue<BigInteger> queue; 

PrimeProducer(BlockingQueue<BigInteger> queue) { 
    this.queue = queue; 
} 

public void run() { 
    try { 
     BigInteger p = BigInteger.ONE; 
     while (!Thread.currentThread().isInterrupted()) 
      queue.put(p = p.nextProbablePrime()); 
    } catch (InterruptedException consumed) { 
     /* Allow thread to exit */ 
    } 
} 

public void cancel() { interrupt(); }} 
+0

對。我認爲這裏的關鍵是任何塊應該拋出InterruptedException。 OP需要顯示阻塞的代碼 – Cruncher