gpt4 book ai didi

java - 如何停止 Java Android 中的线程?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:32 24 4
gpt4 key购买 nike

这是我的测试应用程序的代码:

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 docs .

停止线程的一个好方法是让它退出运行方法。

实现此目的的一种简单方法是向您的线程类添加一个 boolean 成员:

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() 函数。

关于java - 如何停止 Java Android 中的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28519069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com