[英]How to stop a thread in Java Android?
这是我测试应用的代码:
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) {}
}
}
}
}
当我点击“开始”按钮时,线程会成功启动,但是当我单击“停止”按钮时,应用程序崩溃...如何在没有强制关闭的情况下成功停止线程?
非常感谢
不推荐使用Thread.stop()函数,不应该使用它来停止线程。 这是根据java文档 。
停止线程的好方法是让它退出run方法。
实现此目的的一种简单方法是在线程类中添加一个布尔成员:
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) {}
}
}
}
在你的停止按钮onClick方法中调用TestThread.cancel()函数。
除了添加一个布尔来阻止它,我相信你可以捕获InterruptException并只调用Thread.interrupt(); 哪个会退出循环,结束线程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.