多线程分段求和

2023-08-10 15:50:30 浏览数 (1)

思路:先计算每个线程计算的数据范围,使用线程计数器,所有线程计算结束后累加

代码语言:javascript复制
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.SynchronousQueue;

/**
 * @author Zing
 * @create 2022-11-07 14:17
 */
public class MyThread {
    private List list1 = new ArrayList();

    private List list2 = new ArrayList();

//    分段求和
    public long sum(long start,long n){
        long sum = 0;
        for(long i = start;i <= n;i  ){
            sum = i;
        }
        return sum;
    }

    public void sum(){
        long sum = 0;
        for (Object o : list1) {
            sum  = (long) o;
        }
        System.out.println(sum);
    }

//    list2记录每个线程的第一个和最后一个数字
    public void divide(long n,long x){
        long block = n / x;
        long temp = block;
        long j = 1;
        for (long m = 1;m <= x;m  ){
            list2.add(j);
            list2.add(temp);
            j = temp   1;
            temp = block * (m   1);
        }
    }

    public void sunFirst(long n,long x) throws InterruptedException {
        divide(n,x);
        CountDownLatch countDownLatch =new CountDownLatch(list2.size() / 2);
        for(int h = 1;h < list2.size();h =2){
            int finalH = h;
            new Thread(()->{
                long realSum = sum((long) list2.get(finalH - 1),(long) list2.get(finalH));
                System.out.println("real sum"   finalH   ":"   realSum);
                list1.add(realSum);
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        System.out.println("success");
        sum();
    }


}

测试:

代码语言:javascript复制
public class test {
    public static void main(String[] args) throws InterruptedException {

        MyThread myThread = new MyThread();
        myThread.sunFirst(10000,10);

    }
}

计算十亿暴力时间戳差为370,十个线程仅90,这不是最佳匹配,要考虑线程切换资源适配合适的线程数量,但是多线程始终比暴力快

0 人点赞