2013-03-06 20 views
0

我的一條線索是創建另一個線程在特定的時間間隔內執行某些操作。它由定時器來完成。如何正確終止/清除/停止/取消從另一個線程啓動的線程?

現在,當原始線程停止時,另一個線程仍在運行,我無法停止。

我怎樣才能正確地終止了「線」?:

Thread thread = new Thread() { 

    @Override 
    public void run() { 
     try { 
      while (true) { 
       sleep(1000); 
       // do something 
      } 
     } catch (InterruptedException e) { 
      Log.e(TAG,"new invoked caught the exception!"); 
      return; 
     } 
    } 
}; 

public void run() { 
    while (true) { 
     try { 
      Log.d(TAG,"ConnectedThread.run: Reading from InStream socket"); 
      while (true) { 
       thread.start(); 
       Log.e(TAG,"starting additional thread"); 
       // Read from the InputStream 
       int inB; 
       inB = mmInStream.read(); 
       if (inB != -1) mAccessoryInfo.addCharacter((byte) inB); 
      } 
     } catch (IOException e) { 
      Log.e(TAG, "TADA InStream read exception, disconnected " 
        + e.getMessage()); 
      // stopService(new Intent(getBaseContext(), Pinger.class)); 
      thread = null; 
      connectionLost(); 
      break; 
     } 
    } 
} 
+0

一般來說,你不想在你的線程中有一個while(true)循環。創建一個標誌變量(例如「運行」),並使用while(running)代替。這允許線程在運行= false時自行結束,並且可以使用Thread.join()來阻塞,直到它結束。 – thomas88wp 2013-03-06 05:16:42

+0

如果您正在啓動的第二個線程可以按性質在循環中運行,那麼可以考慮使用布爾值來跳出循環並允許它正常終止,而不是中斷它或試圖停止它。就像上面thomas88wp建議的那樣 – 2013-03-06 05:18:35

回答

1
Hi thread is stop by kill() or stop() or destroy method of thread but this all are    
deprecated so dont kill the thread thread is automatically destroy after done its work. 
so 
if you want to do any work use handler like this not thread in therad. 
new Thread() { 

     public void run() { 

      try { 
       Message msg = new Message(); 
       msg.arg2 = 0; 
       handle.sendMessage(msg); 
       Thread.sleep(5000); 
      } catch (Exception e) { 
       Log.e("tag", e.getMessage()); 
      } 

      // 

     } 

    }.start(); 
and make handler in ur activity like this 
public static Handler handle = new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
     super.handleMessage(msg); 
     if (msg.arg2 == 0) { 
      Toast.makeText(context, "No data to sync.",  
    Toast.LENGTH_SHORT) 
        .show(); 
     } else if (msg.arg2 == 1) { 
      Toast.makeText(context, "Data Sync Completed.", 
        Toast.LENGTH_SHORT).show(); 

     } else { 
      Toast.makeText(context, "Data Sync not Completed.", 
        Toast.LENGTH_SHORT).show(); 
     } 

    } 
}; 
0

您將要中斷線程。 「正常」的做法是將while(true)更改爲while(!isInterrupted),但是當您在while循環上方捕獲該異常時,它會在您中斷它時轉到catch-block。您可以致電thread.interrupt()中斷該線程。

0

當你說你有一個「線程」啓動另一個「線程」時有點困惑,你的意思是一個Activity正在啓動一個線程,它是Activity被摧毀,並留下一個孤立的線程運行?如果是這種情況,那麼我會請求關閉Activity'sonDestroy()方法中的線程。

onDestroy()

... 
    if(yourThread != null){ 
    yourThread.interrupt(); 
    } 
    ... 

但我會有點擔心,使用計時器這樣的,有沒有其他的方法來實現自己的目標?即異步任務和使用標誌的任務開始/完成

+0

在將它設置爲null之前,您將不得不中斷'yourThread',否則它會拋出'NullPointerException'。此外,沒有真正的需要將其設置爲空。 – ddmps 2013-03-06 05:18:40

+0

對不對,更新 – wired00 2013-03-06 05:19:41

0

只需在java util併發框架中使用callable語句即可。

父線程代碼會像

public class Worker implements Callable<Boolean> 
{ 
    @Override 
    public Boolean call() throws Exception 
    { 
     //Your worker code here 
    } 
} 

void callingmethod() 
{ 
    //Three threads executing upon five worker modules. 

    ExecutorService executor = Executors.newFixedThreadPool(3); 

    List<Worker> list = new ArrayList<Worker>(5); //For example 5 workers. 

    for(int i=0; i<5; i++) 
    { 
     list.add(new Worker()); 
    } 

    List<Future<Boolean>> futures = executor.invokeAll(list); 

    for(Future<Boolean> future : futures) 
    { 
    future.get(); 
    } 

    executor.shutdown(); 

    executor.awaitTermination(5, TimeUnit.SECONDS); 
} 

聲明的Future.get意味着,在運行調用方法將阻塞,直到所有工人都在進行的工作後返回的線程。