Wait for inline thread to complete before moving to next method

android, java, multithreading

Solution

The Thread instance has a join method, so:

private void onCreate() {
    final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true);

    Thread t = new Thread() {
        public void run() {
            //do some serious stuff...
            dialog.dismiss();           
        }
    };
    t.start(); 
    t.join();
    stepTwo();

}

You may want to try this though:

private void onCreate() {
    final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true);

    Thread t = new Thread() {
        public void run() {
            //do some serious stuff...
            SwingUtilities,invokeLater(new Runnable() {
                public void run() {
                    dialog.dismiss();           
                }
            });
            stepTwo();
        }
    };
    t.start(); 
}

Because onCreate is in the UI thread, having the join in there will freeze the UI till after onCreate completes, saving any dialog till then. `stepTwo` will have to use `SwingUtilities.invokeLater` to do any UI changes itself.

Problem

I have an android app where I am doing the following: ``` private void onCreate() { final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true); new Thread() { public void run() { //do some serious stuff... dialog.dismiss(); } }.start(); stepTwo(); } ``` And I would like to ensure that my thread is complete before stepTwo(); is called. How can I do this? Thanks!

Original source