多线程操作同一个数组,计算数组元素之和
程序员文章站
2024-01-26 08:55:05
...
利用CountDownLatch传入具体的参数。这个参数可以认为是线程的次数(计数器)。每次执行完计数器都会减1.直到为0,主线程开始执行。
public class FiveThreadCount {
private int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28 };
private int total = 0;
public static void main(String[] args) throws InterruptedException{
FiveThreadCount threadCount=new FiveThreadCount();
threadCount.test();
}
public void test() throws InterruptedException {
int length = arr.length;
CountDownLatch latch = new CountDownLatch(length % 5 == 0 ? 5 : 6);
System.out.println("length:" + length + ":" + "latch:" + latch.getCount());
for (int j = 0; j < length; j += length / 5) {
MyThread m = null;
if ((j + (length / 5)) <= length) {
m = new MyThread(arr, j, j + length / 5, latch);
} else {
m = new MyThread(arr, j, length, latch);
}
new Thread(m).start();
latch.await();
System.out.println(total);
}
}
public class MyThread implements Runnable {
int[] arr;
int startIndex;
int endIndex;
CountDownLatch latch;
public MyThread(int[] arr, int startIndex, int endIndex, CountDownLatch latch) {
this.arr = arr;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.latch = latch;
}
@Override
public void run() {
int sum = 0;
for (int i = startIndex; i < endIndex; i++) {
sum += arr[i];
}
synchronized (MyThread.class) {
total += sum;
}
System.out.println(Thread.currentThread().getName());
latch.countDown();
}
}
}
推荐阅读
-
多线程操作同一个数组,计算数组元素之和
-
php中计算二维数组中某一元素之和
-
php数组函数序列之array_sum() - 计算数组元素值之和
-
LeetCode1.两数之和:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,返回数组下标。假设每种输入只对应一个答案。但数组中同一个元素不能使用两遍
-
php数组函数序列之array_sum() - 计算数组元素值之和_php技巧
-
php数组函数序列之array_sum() - 计算数组元素值之和
-
php数组函数序列之array_sum() - 计算数组元素值之和_php技巧
-
php中计算二维数组中某一元素之和
-
php数组函数序列之array_sum - 计算数组元素值之和
-
php数组函数序列之array_sum() - 计算数组元素值之和_PHP教程