Java: multithreading -Wait / notify

I have a class that spawns a bunch of threads and needs to wait until all the generated threads complete. (I need to calculate the completion time of all threads).

MainClass creates all the threads and then checks to see if all the threads are complete before it can call itself complete.

Will this logic work. If so, is there a better way to do this? If not, I would like to better understand this scenario.

class MainClass{
    private boolean isCompleted;
    ...
    for(task : tasks){
        threadpool.execute(task);
    }

    for(task : tasks){
        if(!task.isCompleted()){
            task.wait()
        }
    }

    isCompleted = true;
}


class Task{
    public void run(){
        ....
        ....
        synchronized(this){
            task.completed = true;
            notifyAll();
        }
    }
}
+5
source share
3 answers

notifyAll()relatively slow. Better to use CountDownLatch:

import java.util.concurrent.CountDownLatch;

int n = 10;
CountDownLatch doneSignal = new CountDownLatch(n);
// ... start threads ...
doneSignal.await();

// and within each thread:
doWork();
doneSignal.countDown();
+11
source

/. join(). , MainClass .

, java.util.concurrent.

+4

All this can be done using java.util.concurrent.ExecutorService.

class MainClass {
    ...
    ExecutorService executor = Executors.newCachedThreadPool();
    List<Callable> tasks = ...; // prepare your tasks

    // this invokes all tasks in parallel and waits until all are done
    executor.invokeAll(tasks);
    ...
}

What about that.

+4
source

All Articles