多线程数组求和测试

package cn.wistone.game;

import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* 多线程数组求和 与单循环对比
*
* @author dyx
*
*/
public class SumArrayTest {
private static int innerLength = 10;
private static int outterlength = 10000000;
private static int[][] A = new int[innerLength][outterlength];
public CyclicBarrier cb;
public Long thread_total=new Long(0);
ExecutorService executorService = Executors.newCachedThreadPool();
private static long normal_total;
/**
* 初始化数据
*/
static {
for (int i = 0; i < innerLength; i++) {
for (int j = 0; j < outterlength; j++) {
A[i][j]=i+1;
}
}
}

public SumArrayTest() {
final long start_time = System.currentTimeMillis();
cb = new CyclicBarrier(innerLength, new Runnable() {
public void run() {
long end_time = System.currentTimeMillis();
System.out.println("多线程计算时间:" + (end_time - start_time));
System.out.println("多线程计算结果:" + thread_total);
executorService.shutdown();
}
});

for (int i = 0; i < innerLength; i++) {
executorService.submit(new CalculateArray2(A[i]));
}

}

class CalculateArray2 implements Runnable{
int[] data;

public CalculateArray2(int[] dataTemp) {
data = dataTemp;
}

@Override
public void run(){
long totalNum = 0;
for (int i = 0; i < data.length; i++) {
totalNum += data[i];
}
try {
synchronized (thread_total) {
thread_total += totalNum;
// System.out.println(total);
}
cb.await
} catch (Exception e) {
e.printStackTrace();
}
}
}


class CalculateArray implements Callable<Long> {
int[] data;

public CalculateArray(int[] dataTemp) {
data = dataTemp;
}

public Long call() throws Exception {
long totalNum = 0;
for (int i = 0; i < data.length; i++) {
totalNum += data[i];
}
try {
synchronized (thread_total) {
thread_total += totalNum;
// System.out.println(total);
}
} catch (Exception e) {
e.printStackTrace();
}
cb.await();
return totalNum;
}
}

/**
* 普通方式
*/
public static void count() {
long start_time = System.currentTimeMillis();
for (int i = 0; i < innerLength; i++) {
for (int j = 0; j < outterlength; j++) {
normal_total += A[i][j];
}
}
long end_time = System.currentTimeMillis();
System.out.println("普通计算时间:" + (end_time - start_time));
System.out.println("普通计算结果:" + normal_total);
}


public static void main(String[] args) {
new SumArrayTest();// 多线程方式
SumArrayTest.count(); // 普通循环方式
}

}


结果就不贴了,总体还是多线程并行计算会快10-20 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值