简体   繁体   English

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

[英]How to wait for a thread to finish before another thread starts in 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(); 
} 

However, in this code, the thread apparently starts 10 times at once and it doesn't wait before the previous one is finished. 但是,在此代码中,线程显然一次启动10次,并且在前一个完成之前不会等待。 How do you check if the thread is finished before letting the thread start again? 在让线程再次启动之前,如何检查线程是否完成?

Before answering your question, I strongly encourage you to look into ExecutorServices such as for instance the ThreadPoolExecutor . 在回答您的问题之前,我强烈建议您查看ExecutorServices ,例如ThreadPoolExecutor

Now to answer your question: 现在回答你的问题:

If you want to wait for the previous thread to finish, before you start the next, you add thread.join() in between: 如果要等待上一个线程完成,在开始下一个线程之前,在两者之间添加thread.join()

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

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

If you want to kick off 10 threads, let them do their work, and then continue, you join on them after the loop: 如果你想开始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();

If every thread must wait for the previous one to finish before starting, you'd better have one unique thread executing the original run method 10 times in sequence: 如果每个线程在启动之前必须等待前一个线程完成,那么最好有一个唯一的线程按顺序执行10次原始run方法:

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

Just to elaborate on aioobe's suggestion: 只是详细说明aioobe的建议:

Before answering your question, I strongly encourage you to look into ExecutorServices such as for instance the ThreadPoolExecutor. 在回答您的问题之前,我强烈建议您查看ExecutorServices,例如ThreadPoolExecutor。

There is a particular ExecutorService that can be used for this task: 有一个特定的ExecutorService可用于此任务:

ExecutorService pool = Executors.newSingleThreadExecutor();
for (int i=0; i<10; i++) {
  pool.submit(this); //assuming this is a Runnable
}
pool.shutdown(); //no more tasks can be submitted, running tasks are not interrupted

newSingleThreadExecutor() is similar to calling newFixedThreadPool(1) but ensures that the service cannot be reconfigured to use more than one thread. newSingleThreadExecutor()类似于调用newFixedThreadPool(1)但确保无法将服务重新配置为使用多个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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