【问题标题】:Thread is stopping until the execution of a method is complete. (Android)线程停止,直到方法的执行完成。 (安卓)
【发布时间】:2014-01-02 00:07:10
【问题描述】:

我正在尝试使用一个线程来做一个 Android 游戏,该线程重复一个循环以进行绘制、移动和其他操作。

我在执行方法时遇到问题,该方法使用“do while”循环搜索值。当这个方法被执行时,线程不会继续,直到这个过程没有结束。

避免这种情况的最佳选择是什么?在该方法中创建另一个线程?如果你能举个例子,我真的很感激。

这是一些伪代码:

void mainLoop(){
    drawElements();
    moveElements();
    //...
    //...
    reposition();
}

void reposition(){
    // this stops my thread
    do{
        // do stuff
    }while(!end);

    // do stuff
}

【问题讨论】:

    标签: android runnable ui-thread


    【解决方案1】:

    wqrahd 建议使用 AsyncTask。 我假设 mainLoop 是一个主 UI 线程。

    公共类 RepositionClass 扩展 AsyncTask {

    private Context mContext;
    
    public RepositionClass(Context context) {
        mContext = context;
    }
    
    @Override
    protected void onPreExecute() { 
      // do UI related  here, this function will run in main thread context.
    }
    
    @Override
    protected Boolean doInBackground(String... params) {
       // call non-ui(computation intensive) part of reposition function here. 
       return true;
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
       // do UI related part of reposition function here.
    }
    

    }

    【讨论】:

      【解决方案2】:

      如果您仍然必须阻塞并等待循环完成搜索,那么创建另一个线程将无济于事。问题确实是“做事”循环中发生的事情,您只需要优化它即可解决问题。

      【讨论】:

        【解决方案3】:

        使用 asyntask 并在 asyntask 的 doInBackground 中进行线程工作,并在 asyntask 的 onPostExecute 中调用您的 repositionMethod

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-12
          • 1970-01-01
          • 2021-12-20
          • 1970-01-01
          • 2015-07-04
          相关资源
          最近更新 更多