下面的代码仅启动线程一次,但是我想通过调用下面的方法来停止并重新启动线程。
Thread th;
int t=45;
onstartbuttton()
{
th= new Thread(new callmymethod());
th.start();
}
onstopbutton()
{
}
public class callmymethod implements Runnable {
// TODO Auto-generated method stub
@SuppressWarnings("null")
@Override
public void run() {
// TODO Auto-generated method stub
while(t>-1){
try{
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
time_btn.setText(""+t);
if(t==0)
{
Toast.makeText(getApplicationContext(), "Thread over", Toast.LENGTH_SHORT).show();
}
}
});Thread.sleep(1000);
// Log.i("Thread", "In run"+t);
t=t-1;
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
现在,我想停止线程,因此我必须在onstopbutton()方法中编写什么内容,以及如何通过调用onstartbutton()方法来重新启动。
最佳答案
您需要在线程中添加一个标志,指示它应该停止运行。
您可以使用AtomicBoolean
:
final AtomicBoolean flag = new AtomicBoolean();
onstartbuttton() {
th= new Thread(new callmymethod(flag));
flag.set(true);
th.start();
}
onstopbutton() {
flag.set(false); // indicate that the thread should stop
}
public class callmymethod implements Runnable {
public AtomicBoolean flag;
public callmymethod(AtomicBoolean flag) {
this.flag = flag;
}
@Override
public void run() {
int t = 45; // start back from 45
while(t>-1 && flag.get()){
// do as before
}
}
}
关于android - 如何在需要时停止运行线程并在需要时启动线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23671487/