简体   繁体   English

如何从Android中的另一个方法调用线程内的run方法?

[英]How to call run method inside a thread from another method in android?

I want to make an quiz application in which the questions will be displayed every ten seconds. 我想制作一个测验应用程序,其中每十秒钟显示一次问题。 But when the user answers the question, I need to display the next question. 但是,当用户回答问题时,我需要显示下一个问题。 For this I use threads. 为此,我使用线程。 I have accomplished displaying questions in regular intervals, but when the user answers the question, it wait for the thread to complete. 我已经完成了定期显示问题的操作,但是当用户回答问题时,它会等待线程完成。 I want to stop the thread and start a fresh one on a button click. 我想停止线程并在单击按钮时开始一个新线程。 My code is given below: 我的代码如下:

@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

}

How can I call the run method inside the thread. 如何在线程内调用run方法。 Any help is appreciated. 任何帮助表示赞赏。 Thank you. 谢谢。

You can use t.interrupt() to stop the thread. 您可以使用t.interrupt()停止线程。 Here is the code. 这是代码。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM