如何在Java/Android中另一个线程启动之前等待线程完成?

Zim*_*Zim 19 java multithreading android loops

假设我有这个非常简单的代码:

for(int i = 0; i < 10; i++) { 
    thread = new Thread(this); 
    thread.start(); 
} 
Run Code Online (Sandbox Code Playgroud)

但是,在此代码中,线程显然一次启动10次,并且在前一个完成之前不会等待.在让线程再次启动之前,如何检查线程是否完成?

aio*_*obe 32

在回答你的问题之前,我强烈建议你研究一下ExecutorServices这个问题ThreadPoolExecutor.

现在回答你的问题:

如果要等待上一个线程完成,在开始下一个线程之前,请thread.join()在两者之间添加:

for(int i = 0; i < 10; i++) { 
    thread = new Thread(this); 
    thread.start(); 

    thread.join();    // Wait for it to finish.
}
Run Code Online (Sandbox Code Playgroud)

如果你想开始10个线程,让他们完成他们的工作,然后继续,你join在循环之后对它们:

Thread[] threads = new Thread[10];
for(int i = 0; i < threads.length; i++) { 
    threads[i] = new Thread(this); 
    threads[i].start(); 
}

// Wait for all of the threads to finish.
for (Thread thread : threads)
    thread.join();
Run Code Online (Sandbox Code Playgroud)


JB *_*zet 11

如果每个线程必须在开始之前等待前一个线程完成,那么最好有一个唯一的线程按顺序执行10次原始run方法:

Runnable r = new Runnable() {
    public void run() {
        for (int i = 0; i < 10; i++) {
            OuterClass.this.run();
        }
    }
}
new Thread(r).start();
Run Code Online (Sandbox Code Playgroud)