我想制作一个测验应用程序,其中问题将每十秒显示一次。但是当用户回答问题时,我需要显示下一个问题。为此,我使用线程。我已经完成了定期显示问题,但是当用户回答问题时,它会等待线程完成。我想停止线程并通过单击按钮开始新的线程。我的代码如下:
@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();
}
关于java - 如何从android中的另一个方法调用线程内的run方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32499612/