2012-04-24 73 views
0

因此,活動開始,我創建一個線程來檢查何時進入下一個活動。但有時候我需要這個活動來自殺。 onPause會執行此操作,但在此之後線程仍處於活動狀態,並在時間耗盡後開始新的活動。是否有可能殺死這個線程並停止goToFinals意圖?如何殺死在新活動中運行的線程

public class Questions extends Activity { 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     String in = getIntent().getStringExtra("time");   
     long tmp = Long.parseLong(in); 
     endTime = (long) System.currentTimeMillis() + tmp; 

     Thread progress = new Thread(new Runnable() { 

      public void run() { 
       while(endTime > System.currentTimeMillis()) { 
        try { 
         Thread.sleep(200); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       } 
       Intent goToFinals = new Intent(Questions.this,End.class); 
         startActivity(goToFinals); 
      } 

     }); 
     progress.start(); 

    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     finish(); 
    } 
} 

回答

2

有幾種方法可以阻止你的線程。如果您存儲您Thread對象,然後你可以調用它interrupt()

progress.interrupt(); 

這將導致sleep()拋出InterruptedException,你應該回報,而不是隻打印堆棧跟蹤。你也應該做循環,如:

while(endTime > System.currentTimeMillis() 
    && !Thread.currentThread().isInterrupted()) { 

您還可以設置某種關機標誌的:

// it must be volatile if used in multiple threads 
private volatile boolean shutdown; 

// in your thread loop you do: 
while (!shutdown && endTime > System.currentTimeMillis()) { 
    ... 
} 

// when you want the thread to stop: 
shutdown = true; 
0

爲了安全地退出線程,你必須先調用thread_instance.interrupt(),然後你可以檢查它是否被打斷。 請參閱本LINK

0

看到this職位殺的java他們建議更換thread.The方法是使用共享變量作爲詢問後臺線程停止的標誌。這個變量可以由一個請求線程終止的不同對象來設置。