下面的代码只启动一次线程,但是我想通过调用下面的方法再次停止并启动线程。
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()方法再次启动。
答案 0 :(得分:2)
您需要在线程中添加一个标志,指示它应该停止运行。
您可以使用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
}
}
}