The program I'm supposed to make a program where one thread starts three other threads. The original thread is going to wait until the three other has finished running and then the first thread can stop.

The way I've built the program the three threads is started from one class, let's call it FirstThread. The FirstThread class is started as a thread from main, and it only contains a run-method that starts up and shuts down the three threads. This seems to work in some way. But how do I make the first thread (started from main) to wait until the three other threads is finished before it finishes to?

Parts of the code:

Main:

import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class Main
    {
     
        public static void main(String[] args)
        {
            ExecutorService thread = Executors.newCachedThreadPool();
            RingBuffer share = new RingBuffer();
     
            thread.execute(new FirstThread(share));
     
            thread.shutdown();
       } // end main
    } // end class main

The FirstThread:

import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
     
    public class FirstThread implements Runnable
    {
     
        ExecutorService thread = Executors.newCachedThreadPool();
        RingBuffer share = new RingBuffer();
     
        public FirstThread(Buffer share)
        {
            this.share = share;
        } // end constructor
     
        public synchronized void run()
        {
            share.outPut("Test");
     
            thread.execute(new Son1(share));
            thread.execute(new Son2(share));
            thread.execute(new Son3(share));
     
            thread.shutdown();
        } // end method
    } // end class

Recommended Answers

All 5 Replies

Keep debugging. That example is the right solution. Put lots of print statements in your code so you can see what it's doing.

Create a instance variable of type CountDownLatch in the FirstThread class with the initial value of the number of threads for which you want to wait (3 in your case). Pass this instance to the constructors of the thread class for which you'd want to wait. As the final statement of the run() method of your FirstThread class, invoke the await() method of that latch which would "wait" till the latch count reaches 0. At the end of each threads' processing, decrement the count of the latch. By the time your dependent threads are competed, the value of the latch would become 0 which in turn would "wake" up the FirstThread thread.

I have worked it out! Thanks for response and help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.