现在 先看一个 使用Runnable接口实现求数值积分的java多线程并行程序如下(电脑是四核,并行3个线程):
package com.xing.add;
/**
*
* @author Yinxing
*
*/
public class PI_Runnable {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//-------------------------并行运算------------------------------
long startTime ,endTime;
double step = 1.0 / 100000000;
works works1 = new works(1, 100000000);
works works2 = new works(2, 100000000);
works works3 = new works(3, 100000000);
Thread thread1 = new Thread(works1);
Thread thread2 = new Thread(works2);
Thread thread3 = new Thread(works3);
startTime = System.currentTimeMillis();//获取并行计算的开始时的系统时间
thread1.start();
thread2.start();
thread3.start();
thread1.join();//实现线程并行
thread2.join();
thread3.join();
endTime = System.currentTimeMillis();//获取并行计算的结束时的系统时间
long ParallelTime = endTime - startTime;
System.out.println("PI(π) = "+ (works1.getSum() + works2.getSum() + works3.getSum()) * step);//并行计算求的PI(π)值
System.out.println("Runnable求PI(π)并行时间:"+ ParallelTime);
//---------------------------串行运算---------------------------------
works works5 = new works(1, 100000000);
startTime = System.currentTimeMillis();//获取串行计算的开始时的系统时间
double PI = works5.GetPI();
endTime = System.currentTimeMillis();//获取串行计算的结束时的系统时间
long SeriaTime = endTime - startTime;
System.out.println("PI(π) = "+ PI * step);//串行计算求的PI(π)值
System.out.println("求PI(π)串行时间:"+ SeriaTime);
//------------------------------输出相对加速比-------------------------
System.out.println("相对加速比: "+SeriaTime +"/"+ParallelTime);
}
}
class works implements Runnable{
private long start;
private long end ;
private double sum;
private double step;
private long num_steps = 100000000;
public works(long start,long end){
super();
this.start = start;
this.end = end;
}
@Override
public void run() {
// TODO Auto-generated method stub
double x = 0;
step = 1.0 / (double) num_steps;
for (long i = start; i <= end; i += 3) {
x = (i + 0.5) * step;
sum = sum + 4.0 / (1.0 + (x*x));
}
}
public double GetPI(){
double x = 0;
step = 1.0 / (double) num_steps;
for (long i = start; i <= end; i ++) {
x = (i + 0.5) * step;
sum = sum + 4.0 / (1.0 + (x*x));
}
return sum;
}
public double getSum() {
return sum;
}
}
运行结果如下:
我们可以看出线程
thread1.start();
thread2.start();
thread3.start();
在调用join()方法
thread1.join();//实现线程并行
thread2.join();
thread3.join();
使其同时在多核上并行处理。由于其他的因素 加速比 1350/460=2.9347826086956 虽然不等于3,但是并行的效果是显而易见的