等待Android中的子模块初始化

时间:2013-12-13 10:02:10

标签: java android multithreading synchronization

我有应用程序,其中我开始几个线程,每个都有一个子模块。 线程启动后,子模块正在初始化然后运行。

public class MySubmoduleThread extends Thread {
    ...
    private MySubmodule mSubmodule;
    ...
    @Override
    public final void run() {
        mSubmodule.initialize();
        mSubmodule.run();
    }
}

这些线程在应用程序onCreate上启动。等待所有子模块初始化的简单方法是什么?

public class MyApp extends Application {
    ...
    @Override
    public void onCreate() {
        super.onCreate();
        ...
        mSubmoduleThread1.start();
        mSubmoduleThread2.start();
        ...
        mSubmoduleThreadN.start();
        --> waitSomehowUntilAllSubmodulesAreInitialized
        ...
    }

当然,我可以修改MySubmoduleThread代码,以便在mSubmodule.initialize();mSubmodule.run();之间添加内容。

1 个答案:

答案 0 :(得分:1)

考虑不要等待。阻止主线程不是一个好主意。使用子模块的地方可能会异步访问它们并在需要时等待。

否则请使用CountDownLatch包中的Semaphorejava.util.concurrent,..

public class MySubmoduleThread extends Thread {
    ...
    private MySubmodule mSubmodule;
    private CountDownLatch mLatch; // shared latch object accross tasks
    public MySubModuleThread(CountDownLatch latch) {
        mLatch = latch;
    }
    ...
    @Override
    public final void run() {
        mSubmodule.initialize();
        mLatch.countDown(); // count 1 down
        mSubmodule.run();
    }
}

public class MyApp extends Application {
    ...
    @Override
    public void onCreate() {
        super.onCreate();
        int nrOfTasks = /* N */;
        CountDownLatch latch = new CountDownLatch(nrOfTasks);
        mSubmoduleThread1 = new SubModuleThread(latch);
        mSubmoduleThread2 = new SubModuleThread(latch);
        ...
        mSubmoduleThread1.start();
        mSubmoduleThread2.start();
        ...
        mSubmoduleThreadN.start();

        latch.await(); // wait that countdown reaches 0 (needs some try catch)

    }