仅在所有线程完成后如何执行一段代码 [英] How to execute a piece of code only after all threads are done

查看:94
本文介绍了仅在所有线程完成后如何执行一段代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日志记录代码,需要在所有Threads执行完之后执行.

I have a logging code which needs to be executed after all Threadss are executed.

Thread t1 = new MyThread();
Thread t2 = new MyThread();
t1.run();
t2.run();

doLogging();

只有在两个线程都完成处理后,才可以执行doLogging()的任何方法.现在,一旦启动t1和t2,就会调用doLogging().

Is there any way to execute doLogging() only after both threads are done with their processing. Now that doLogging() is called as soon as t1 and t2 are started.

推荐答案

只需

Just join() all threads before your doLogging() call:

t1.join();
t2.join();

// the following line will be executed when both threads are done
doLogging();

请注意,如果要等待所有线程,则join()调用的顺序无关紧要.

Note that the order of join() calls doesn't matter if you want to wait for all of your threads.

这篇关于仅在所有线程完成后如何执行一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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