下面的代码仅启动线程一次,但我想通过调用下面的方法来停止并再次启动线程。
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/