Why does my Thread freeze the UI-Thread?

IAmGroot picture IAmGroot · Sep 3, 2013 · Viewed 7.1k times · Source

I cant figure it out.

For what ever reason, this thread's code is actually running on the UI thread. If i break point it the UI stops. or Sleep it, UI stopped. and hence network activity is unallowed as its on the "ui" thread.

Ive not used Async task, because I am unaware of the proper way of looping it. (calling a new instance of it in onPostExecute seems like bad practice, and as if async is for one off tasks.

I extend Thread.

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();      
    }   
}   

ANd from my Activity I call

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

Answer

Philipp Jahoda picture Philipp Jahoda · Sep 3, 2013

You should use Thread.start() to start any new thread. As far as I know calling run() directly will not cause the system to actually launch a new thread, hence your blocking UI.

Change your startThread() method to the following and it should then work:

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 for more specific information from the Java revisited blog.