如何在Java / Android中另一个线程启动之前等待线程完成? [英] How to wait for a thread to finish before another thread starts in Java/Android?

查看:498
本文介绍了如何在Java / Android中另一个线程启动之前等待线程完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I've got this very simple code:

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

但是,在此代码中,线程显然一次启动10次在前一个完成之前不等待。如何在让线程重新开始之前检查线程是否已完成?

However, in this code, the thread apparently starts 10 times at once and it doesn't wait before the previous one is finished. How do you check if the thread is finished before letting the thread start again?

推荐答案

在回答您的问题之前,我强烈建议您查看 ExecutorServices ,例如 ThreadPoolExecutor

Before answering your question, I strongly encourage you to look into ExecutorServices such as for instance the ThreadPoolExecutor.

现在回答你的问题:

如果你想等待上一个线程完成,在你开始下一个线程之前,你在之间添加 thread.join()

If you want to wait for the previous thread to finish, before you start the next, you add thread.join() in between:

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

    thread.join();    // Wait for it to finish.
}






如果你想踢关闭10个线程,让他们完成他们的工作,然后继续,循环后你加入

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

这篇关于如何在Java / Android中另一个线程启动之前等待线程完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆