我对Java编程非常陌生,并且遇到线程中while循环的麻烦。我在这里发布一个我使用while循环的例子。应用程序与线程崩溃
public class MainActivity extends AppCompatActivity {
private boolean running = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView)findViewById(R.id.textView);
new Thread(new Runnable() {
@Override
public void run() {
while (running) {
try{Thread.sleep(1000);}
catch(InterruptedException e){}
running = false;
text.setText("false!");
running = true;
try{Thread.sleep(1000);}
catch(InterruptedException e){}
text.setText("True!");
}
}
}).start();
}
}
当运行设置为false时,线程不会运行,应用程序不会显示任何内容。当运行设置为true时,应用程序崩溃后 text.setText(“false!”);
谢谢大家提前!
阅读异常消息(并将其发布到您的问题中)。它应该告诉你,你不能更新UI线程之外的用户界面 – AxelH
看看logcat并发布堆栈跟踪 – Jens
这个[answer](http://stackoverflow.com/a/5185140/4391450)是最简单的使用 – AxelH