如何延迟主线程直到子线程完成?

时间:2014-07-30 01:56:54

标签: android multithreading

问题与标题相同。
 怎么做?

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

2 个答案:

答案 0 :(得分:0)

您可以使用:

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

Thread类文档位于http://developer.android.com/reference/java/lang/Thread.html

编辑: 只需阅读评论。我同意迈克的观点。这是你提出要求的方式,但这不是解决问题的方法。

答案 1 :(得分:0)

添加界面:

public interface CountingListener{
    public void countingDone();
}

然后你需要一个对主线程的引用,所以你可以从你的“计数”线程中调用它。

final Handler mainThread = new Handler();

这是完整的代码:

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

}

这应该可以,而不会阻止你的主线程。