In my program, I am creating several threads in the main() method. The last line in the main method is a call to System.out.println(), which I don\'t want to call until all
You could share a CyclicBarrier
object among your RaceCar
s and your main thread, and have the RaceCar
threads invoke await()
as soon as they are done with their task. Construct the barrier with the number of RaceCar
threads plus one (for the main thread). The main thread will proceed when all RaceCar
s have finished.
See http://java.sun.com/javase/6/docs/api/java/util/concurrent/CyclicBarrier.html
In detail, construct a CyclicBarrier
in the main thread, and add a barrier.await()
call in your RaceCar
class just before the run()
method exits, also add a barrier.await()
call before the System.out.println()
call in your main thread.
You could make the last line be in a "monitoring" thread. It would check every so often that it is the only running thread and some completion state == true
and then could fire if it was. Then it could do other things than just println
Simplest way
while (Thread.activeCount() > 1) {
}
I know it block main thread... but it works perfectly!