2012-04-24 78 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方法是使用共享变量作为询问后台线程停止的标志。这个变量可以由一个请求线程终止的不同对象来设置。