[英]How to stop a thread in Java Android?
This is the code of my testing app: 这是我测试应用的代码:
public class MainActivity extends Activity
{
private TextView text;
private Button start;
private Button stop;
private TestThread Points;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView) findViewById(R.id.mainTextView1);
start = (Button) findViewById(R.id.mainButton1);
stop = (Button) findViewById(R.id.mainButton2);
Points = new TestThread();
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{
if (! Points.isAlive())
{
Points.start();
}
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View p1)
{
if (Points.isAlive())
{
Points.stop();
}
}
});
}
public class TestThread extends Thread
{
private String points;
@Override
public void run()
{
for (int a = 0; a < 3; a++)
{
try
{
if (a == 0) points = ".";
else if (a == 1) points = "..";
else if (a == 2) {
points = "...";
a = -1;
}
runOnUiThread(new Runnable()
{
@Override
public void run()
{
text.setText(points);
}
});
Thread.sleep(350);
} catch (InterruptedException e) {}
}
}
}
}
When I click on Start button the thread starts successfully but when I click on Stop button the app crashes... How can i stop the thread successfully without force closing? 当我点击“开始”按钮时,线程会成功启动,但是当我单击“停止”按钮时,应用程序崩溃...如何在没有强制关闭的情况下成功停止线程?
Thanks a lot 非常感谢
Thread.stop() function is deprecated and should not be used to stop a thread. 不推荐使用Thread.stop()函数,不应该使用它来停止线程。 this is according to the java docs . 这是根据java文档 。
a good way to stop a thread is make it exit its run method. 停止线程的好方法是让它退出run方法。
a simple way to achive this is by adding a boolean member to your thread class: 实现此目的的一种简单方法是在线程类中添加一个布尔成员:
public class TestThread extends Thread
{
private String points;
private boolean keepRunning = true;
public cancel(){
keepRunning = false;
}
@Override
public void run()
{
for (int a = 0; a < 3; a++)
{
if(!keepRunning) break;
try
{
if (a == 0) points = ".";
else if (a == 1) points = "..";
else if (a == 2) {
points = "...";
a = -1;
}
runOnUiThread(new Runnable()
{
@Override
public void run()
{
text.setText(points);
}
});
Thread.sleep(350);
} catch (InterruptedException e) {}
}
}
}
call the TestThread.cancel() function in your stop button onClick method. 在你的停止按钮onClick方法中调用TestThread.cancel()函数。
Other than adding a Boolean to stop it I believe you could catch InterruptException and just call Thread.interrupt(); 除了添加一个布尔来阻止它,我相信你可以捕获InterruptException并只调用Thread.interrupt(); which would exit the loop this ending the thread 哪个会退出循环,结束线程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.