java 多线程并行求数值积分(πPI) 之 join() 方法应用

24 篇文章 2 订阅
14 篇文章 0 订阅

现在 先看一个 使用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,但是并行的效果是显而易见的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值