Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until child threads completed : Java

Problem description : -

Step 1: Take input FILE_NAME from user at main thread.

Step 2: Perform 10 operations on that file (i.e count chars, count lines etc.. ), and all those 10 operations must be in septate threads. It means there must be 10 child threads.

Step 3: Main thread waits until all those child threads completed.

Step 4: Print result.

What I did :-

I did a sample code with 3 threads. I don't want file operation code from your side.

public class ThreadTest {
    // This is object to synchronize on.
    private static final Object waitObject = ThreadTest.class;
    // Your boolean.
    private static boolean boolValue = false;

    public final Result result = new Result();

    public static void main(String[] args) {
        final ThreadTest mytest = new ThreadTest();

        System.out.println("main started");

        new Thread(new Runnable() {

            public void run() {
                System.out.println("Inside thread");

                //Int initialiser
                new Thread(new Runnable() {

                    public void run() {
                        System.out.println("Setting integer value");
                        mytest.result.setIntValue(346635);
                        System.out.println("Integer value seted");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }).start();

                //String initialiser
                new Thread(new Runnable() {

                    public void run() {
                        System.out.println("Setting string value");
                        mytest.result.setStringValue("Hello hi");
                        System.out.println("String value seted");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }).start();

                //Boolean initialiser
                new Thread(new Runnable() {

                    public void run() {
                        System.out.println("Setting boolean value");
                        mytest.result.setBoolValue(true);
                        System.out.println("Boolean value seted");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }).start();

                System.out.println("Thread is finished");

                //Notify to main thread
                synchronized (ThreadTest.waitObject) {
                    ThreadTest.boolValue = true;
                    ThreadTest.waitObject.notifyAll();
                }               
            }
        }).start();

        try {
            synchronized (ThreadTest.waitObject) {
                while (!ThreadTest.boolValue) {
                    ThreadTest.waitObject.wait();
                }
            }
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }

        System.out.println("main finished");
        System.out.println("Result is : " + mytest.result.toString());
    }
}

Problem :-

My above code is not giving correct answer. How can I do that?

Alternate solutions:

CountDownLatch class does the same. But I don't want to use that class.

I looked this similar solution and I want to use methods of Thread only.

like image 410
Andy Avatar asked Mar 30 '12 07:03

Andy


People also ask

Which method is wait for child thread to finish?

In java Thread join method is used, so that main or parent thread can wait for its child thread to finish its execution and die. After that only main thread can executes its further statements.

Which method is used to wait for a child to finish in java?

The wait() is used in with notify() and notifyAll() methods, but join() is used in Java to wait until one thread finishes its execution.

Is wait () in thread class?

Hence, wait() and notify() methods are defined in Object class rather than Thread class. If wait() and notify() were on the Thread instead then each thread would have to know the status of every other thread and there is no way to know thread1 that thread2 was waiting for any resource to access.


2 Answers

You can do:

Thread t = new Thread() {
    public void run() {
        System.out.println("text");
        // other complex code
    }
 };
 t.start();
 t.join();

This way you will wait until the thread finishes and just then continue. You can join multiple threads:

for (Thread thread : threads) {
  thread.join();
}
like image 178
Boris Strandjev Avatar answered Sep 28 '22 10:09

Boris Strandjev


I would recommend looking at the Executors framework first, and then look into the CompletionService.

Then you can write something like this:

ExecutorService executor = Executors.newFixedThreadPool(maxThreadsToUse);
CompletionService completion = new ExecutorCompletionService(executor);
for (each sub task) {
    completion.submit(new SomeTaskYouCreate())
}
// wait for all tasks to complete.
for (int i = 0; i < numberOfSubTasks; ++i) {
     completion.take(); // will block until the next sub task has completed.
}
executor.shutdown();
like image 39
daveb Avatar answered Sep 28 '22 09:09

daveb