简体   繁体   中英

How to delay main thread until subthread is finished?

Question is same with title.
How to do that?

public class Main_Activity extends Activity {
    int threadCount = 0;
    int mainCount = 500;

    @override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);

        Thread t_thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<100000;i++) {
                    threadCount++;
                }
            }
        }

        t_thread.start();

        // main thread.
        // how to delay a main thread until subthread is finished?
        mainCount += threadCount;

        // wanted result is 100500
        Log.i("MyTag", "" + mainCount);
    }
}

You can use:

try{
    t_thread.join();
} catch(InterruptedException e){
    // something useful
}

The Thread class doc is at http://developer.android.com/reference/java/lang/Thread.html

EDIT: Just read the comments. I agree with Mike. This is the way to do what you asked, but it isn't the way to solve your problem.

Add an interface:

public interface CountingListener{
    public void countingDone();
}

Then you'll need a reference to the main thread, so you can call it from your "counting" thread.

final Handler mainThread = new Handler();

This is the complete code:

public class Main_Activity extends Activity {
int threadCount = 0;
int mainCount = 500;

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

    final Handler mainThread = new Handler();

    final CountingListener listener = new CountingListener() {
        @Override
        public void countingDone() {
            // main thread.
            // how to delay a main thread until subthread is finished?
            mainCount += threadCount;

            // wanted result is 100500
            Log.i("MyTag", "" + mainCount);

        }

    };

    Thread t_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 100000; i++) {
                threadCount++;
            }

            mainThread.post(new Runnable() {
                @Override
                public void run() {
                    listener.countingDone();
                }
            });
        }
    });

    t_thread.start();

}

This should work, without blocking your main thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM