0

I created simple example in Android: on a button click, a new Thread is created run in backgroud. However when I put it to sleep (Thread.sleeps(10000)) it blocks also the UIThread.

Why it blocks also the UIThread? My thread is supposed to run in background in asynchronous way. Is there any way to run a Thread in background without using AsyncTask and doInBackground method? Any suggestions?

Thanks in advance

Here the code:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) { return true;  }
        return super.onOptionsItemSelected(item);
    }

    public void dothings(View view){
        new Thread(){
            public void run(){
                try{Thread.sleep(10000);}
                catch(Exception e){}
            }
        }.run();

        Toast.makeText(getApplicationContext(),"CIao",Toast.LENGTH_SHORT).show();

    }
}
Enrico
  • 41
  • 1
  • 4

2 Answers2

0

you need to call Start() function and not run() function

Itzik Samara
  • 2,278
  • 1
  • 14
  • 18
0

To provide more details on Itzik's answer which is correct, by calling run() on the thread instance you are actually executing the run method in which you defined the sleep to happen. You're seeing the UI freeze up for those 10 seconds since this is being called from the main thread.

start() will actually begin the execution of the thread, with the VM executing the run() method of the thread.

Martin
  • 1,775
  • 1
  • 13
  • 10