[英]How to call run method inside a thread from another method in android?
我想制作一个测验应用程序,其中每十秒钟显示一次问题。 但是,当用户回答问题时,我需要显示下一个问题。 为此,我使用线程。 我已经完成了定期显示问题的操作,但是当用户回答问题时,它会等待线程完成。 我想停止线程并在单击按钮时开始一个新线程。 我的代码如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (i++ < 10) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
//Display questions here
}
});
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
public void buttonOnClick(View view)
{
//I want to display new question here
}
如何在线程内调用run方法。 任何帮助表示赞赏。 谢谢。
您可以使用t.interrupt()停止线程。 这是代码。
Thread t ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateQuestions()
}
public void generateQuestions()
{
t = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
try {
while (i++ < 10 & !Thread.currentThread().isInterrupted()) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//Display questions here
}
});
Thread.sleep(6000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
public void buttonOnClick(View view)
{
//I want to display new question here
t.interrupt();
generateQuestions();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.