【问题标题】:Why does my Thread freeze the UI-Thread?为什么我的线程冻结 UI 线程?
【发布时间】:2013-09-03 14:07:04
【问题描述】:

我想不通。

出于某种原因,这个线程的代码实际上是在 UI 线程上运行的。 如果我断点它 UI 停止。或睡眠它,用户界面停止。因此,网络活动在“ui”线程上是不允许的。

我没有使用异步任务,因为我不知道循环它的正确方法。 (在 onPostExecute 中调用它的新实例似乎是一种不好的做法,并且好像 async 用于一次性任务。

我扩展线程。

public class SyncManager  extends Thread {

public SyncManager(Context context){
    sdb = new SyncManagerDBHelper(context);
    mContext = context;     
}

@Override
public void run() {     

    while(State == RUNNING) {
        try{
            SyncRecords();   // Break point here = UI freeze.
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(10000); // So also causes UI freeze.
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 public void startThread() {
    Log.i("SyncManager", "start called");

    if((State == PAUSED || State == STOPPED) && !this.isAlive() )
    {
        State = RUNNING;
        run();      
    }   
}   

我从我的活动中调用

  sm = new SyncManager(this);
  sm.startThread();

【问题讨论】:

标签: android multithreading networking freeze ui-thread


【解决方案1】:

您应该使用Thread.start() 来启动任何新线程。 据我所知,直接调用run()不会导致系统实际启动新线程,因此会阻塞用户界面。

将您的 startThread() 方法更改为以下内容,然后它应该可以工作:

public class SyncManager extends Thread {

    public void startThread() {

        if((State == PAUSED || State == STOPPED) && !this.isAlive()) {
            State = RUNNING;
            start();  // use start() instead of run()
        }   
    }
}

Read here 可从 Java 重访博客获取更多具体信息。

【讨论】:

  • 叹息,我知道这是个愚蠢的问题。具有讽刺意味的是,我写了一个测试线程,并把start(); 话虽这么说,如果我没有问,我会浪费更多的时间来弄清楚它。现在确实有意义。调用run() 只是调用UI 线程上的方法,就像直接调用任何方法一样。谢谢!
  • 2 年后,是的,它帮助了我 =D
猜你喜欢
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多