多线程数组求和测试

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

你可能感兴趣的:(thread,多线程)