categories: java
tags:
- CountDownLatch
- 多线程
使用 CountDownLatch 多线程累加求和
package thread;
import java.util.*;
import java.util.concurrent.CountDownLatch;
public class addNumber {
// TreeMap 能够把它保存的记录根据key排序,默认是按升序排序,也可以指定排序的比较器,
// 当用Iterator 遍历TreeMap时,得到的记录是排过序的。TreeMap不允许key的值为null。非同步的
private static final Map<Long, Integer> MAP = new TreeMap<>();
public static void main(String[] args) throws InterruptedException {
//累加值
long longer=200_0000_0000L;
//最大线程数
long threadCount=10000L;
//单线程
singleThread(longer);
//多线程
multiThread(longer,threadCount);
}
static void multiThread(long longer, long threadCount) throws InterruptedException {
for (int i = 0; i <= threadCount; i+=100) {
if (i!=0&&longer%i==0) {
multiThreading(longer/i,i);
}
}
Iterator<Map.Entry<Long, Integer>> iterator = MAP.entrySet().iterator();
//使用迭代器获取第一个元素
Map.Entry<Long, Integer> next = iterator.next();
//取出用时最短的线程数
Long key = next.getKey();
System.out.println("用时最小的线程是:"+MAP.get(key)+" 线程\t用时: "+key+" 毫秒");
}
/**
* 单线程累加
*/
static void singleThread(long longer) {
long sum = 0L;
long start = System.currentTimeMillis();
for (long i = 1L; i <= longer; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println("单线程用时: " + (end - start) + " 毫秒\t结果: " + sum);
}
/**
* 多线程累加
*
* @param shard 分片
* @param threadCount 线程数
* @throws InterruptedException 中断异常
*/
static void multiThreading(long shard,int threadCount) throws InterruptedException {
long sum=0L;
long start = System.currentTimeMillis();
//允许一个或多个线程等待直到在其他线程中执行的一组操作完成的同步辅助。
//threadCount 计数器
CountDownLatch countDown=new CountDownLatch(threadCount);
Multithreading[] multithreadings = new Multithreading[threadCount];
for (int i = 1; i <= threadCount; i++) {
multithreadings[i-1]=new Multithreading(countDown,(i - 1) * shard +1, shard * i);
new Thread(multithreadings[i-1]).start();
}
//main线程进入等待
countDown.await();
for (int i = 1; i <= threadCount; i++) {
sum = sum + multithreadings[i-1].getSum();
}
long end = System.currentTimeMillis();
System.out.println(threadCount+"线程用时: " + (end - start) + " 毫秒\t结果: " + sum);
MAP.put((end - start),threadCount);
}
}
class Multithreading implements Runnable {
CountDownLatch countDown;
long start, end, sum;
Multithreading(CountDownLatch countDown, long start, long end) {
this.countDown = countDown;
this.start = start;
this.end = end;
}
@Override
public void run() {
for (long i = start; i <= end; i++) {
sum += i;
}
//计数器减一
countDown.countDown();
}
public long getSum() {
return sum;
}
}