开发者

Java - phasing threads

I'm implementing a parallel, performance-critical algorithm with multiple threads. I assign all threads some data to work on. When all those threads have finished to work on their data, I assign all threads new data, and the cycle continues. (This is what I refer to as thread "clocking" since it's somewhat similar to CPU clocking.)

What I came up with so far is using a master thread that stores an integer. At the beginning of each cycle, I set the integer to the number of slave threads. When a slave thread is done, it decrements the master thread's integer. Once that integer reaches zero, I开发者_如何学Go start a new cycle.

Is this a good approach, or are there more efficient ways of doing the same thing?


You'd be better off using a Phaser (if you have Java 7), or CyclicBarrier for Java 5+.


I would recommend looking at the newer classes in the java.util.concurrent package, especially ThreadPoolTaskExecutor. You might be reinventing the wheel if you haven't looked beyond java.lang.Thread.


Well. See CyclicBarrier (JavaDoc)


A better way is to use Thread.join(). In you main thread, you call join() on all the threads you are starting. The main thread will wait untill all joined threads are finished.

See for example http://javahowto.blogspot.com/2007/05/when-to-join-threads.html


An ExecutorService can do this for you.

ExecutorService executor = Executors.newFixedThreadPool(10);

do {
  List<Callable> tasks = getNextTasksToExecute();
  executor.invokeAll(tasks);
} while (tasks.size() > 0);

This will create a thread pool with 10 threads. It will then call getNextTasksToExecute() which you should implement yourself to return the next bunch of tasks that need doing. It will execute those tasks in parallel in the thread pool and then keep looping until getNextTasksToExecute() returns no more tasks.

Edit:
Code not tested, think there may be a compile error, but you can figure that out.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜