需求:
1:对一个大数组进行求和。
2:需要使用多线程实现。
思路:
1:将大数组根据线程的数量进行拆分。
2:每个线程对数组的部分元素进行求和。
3:等待所有线程执行完毕,返回结果。
说明:
在论坛中看到有一个帖子是使用concurrent包实现的,我这个例子没有使用concurrent包。发现也挺简单。
代码如下所示:
/**
* 多线程求和
* @author Administrator
*
*/
public class ThreadsSum {
static public long sum(final int[] array) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException("array length must greater than 0");
}
final RuntimeData rd = new RuntimeData();
int threadCount = rd.getThreadCount(array);
System.out.println("thread count:" + threadCount);
//每线程计算的数组元素个数
final int lenPerThread = array.length / threa