开发者

Java : Multithreading -Wait/notifyAll Question

I have a class which spawns a bunch of threads and have to wait till all the spawned threads are completed. ( I need to calculate the time for all threads to complete).

The MainClass spawns all the threads and then it checks whether all the threads are completed before it can call itself completed.

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 is开发者_JAVA技巧Completed;
    ...
    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();
        }
    }
}


notifyAll() is relatively slow. A better way is 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();


There's no need for wait/notify in this case. You can just loop through the threads and call join(). If the thread's already finished, the MainClass thread will just wait for the next one.

You might want to have a look at the higher-level utilities in the java.util.concurrent package too.


All this can be done by 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);
    ...
}

That's about it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜