How to execute a piece of code only after all threads are done

筅森魡賤 提交于 2020-04-10 08:00:20

问题


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

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.


回答1:


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

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

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

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




回答2:


In addition to the join() solution there is also something called CountDownLatch in the java.util.concurrent library. It allows you to initialize it to a certain number and then wait until it was hit the specified number of times.

Simple example:

CountDownLatch latch = new CountDownLatch(NUMBER_OF_THREADS);
for(int i=0; i<NUMBER_OF_THREADS;i++)
   new Thread(myCode).start();

latch.await();

The latch must be explicitly hit by the worker threads for this to work though:

latch.countDown()



回答3:


If you are running the code from the main thread, bear in mind that it will cause the UI to hang until both threads complete. This may not be the desired effect.

Instead, you could consider a construction where each thread synchronizes over your Logger object and perform calls to it within that construct. Since I don't know what you are specifically trying to accomplish, the other solution is what Joachim suggested, only placing that code within a thread.



来源:https://stackoverflow.com/questions/1492069/how-to-execute-a-piece-of-code-only-after-all-threads-are-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!