Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of achieving this threading/event behaviour in Java?

I have a thread (Runnable) that starts a number of other threads (Runnables). When each child thread finishes it needs to raise an event (or something similar) and return a notification to the parent thread. I can't see any events in Java (ala C#) - I had hoped I could just subscribe in the parent to the child object's 'I'm finished event' but it doesn't appear I can do that. How do you suggest I accomplish this?

Thanks

like image 415
MalcomTucker Avatar asked Jan 23 '23 11:01

MalcomTucker


1 Answers

Java has a CountDownLatch in its threading library. Create a CountDownLatch and initialize it with the number of threads you're going to run. When you're creating your threads you should give them the latch and each thread will signal on it when it's finished. Your main thread will block until all of the worker threads have finished.

With CountDownLatch you will achieve a lock-free communication with your threads.

Directly from Java's documentation:

 class Driver { // ...
   void main() throws InterruptedException {
     CountDownLatch startSignal = new CountDownLatch(1);
     CountDownLatch doneSignal = new CountDownLatch(N);

     for (int i = 0; i < N; ++i) // create and start threads
       new Thread(new Worker(startSignal, doneSignal)).start();

     doSomethingElse();            // don't let run yet
     startSignal.countDown();      // let all threads proceed
     doSomethingElse();
     doneSignal.await();           // wait for all to finish
   }
 }

 class Worker implements Runnable {
   private final CountDownLatch startSignal;
   private final CountDownLatch doneSignal;
   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
      this.startSignal = startSignal;
      this.doneSignal = doneSignal;
   }
   public void run() {
      try {
        startSignal.await();
        doWork();
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
   }

   void doWork() { ... }
 }

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html

like image 71
Kiril Avatar answered Feb 03 '23 06:02

Kiril