Java多线程系列(2)

可并行化的算法:某个CPU上运行循环的迭代的同时,另一个CPU上运行另一个循环的迭代。之间数据的依赖性可能会禁止某特定的循环被并行化,但是对于CPU密集的程序,将可能的循环并行化可以大幅提高程序运行速度。(by Johnny Deng)

Java的编译器不支持循环并行的自动化,但是我们可以了手动的实现一下。举例:

原程序:

/*-**************************************************************/
 *
 *      Package Name: seibuaa.concurrency
 *      File    Name; PowerTable.java
 *      Description :
 *      Author      : DengXiong
 *      Copyright   : SEI BUAA
 *      Date        : 2006-10-20
 *
/*-**************************************************************/
package seibuaa.concurrency;

public class CosTable {
 
 private volatile double CosTable[] = null;
 
 public synchronized double[] getValues(){
  if (this.CosTable == null) return CosTable = new double[100*100];
  for (int i = 0; i < 100*100; i++){
   double cosValue = (double)Math.cos(i % 360) * Math.PI / 180.0;
   this.CosTable[i] = cosValue * (double)i / 180.0d;
  }
  return this.CosTable;
  
 }

}

 

修改后的程序:

/*-**************************************************************/
 *
 *      Package Name: seibuaa.concurrency
 *      File    Name; CosTableConCurrency.java
 *      Description :
 *      Author      : DengXiong
 *      Copyright   : SEI BUAA
 *      Date        : 2006-10-20
 *
/*-**************************************************************/
package seibuaa.concurrency;

public class CosTableConCurrency implements Runnable{
 private class CosTableRanges{
  public int start, end;
 }
 
 private volatile double cosTable[];
 private int startLoop, curLoop, endLoop, numThreads;

 
 private Thread cosThread[];
 
 public CosTableConCurrency(){
  this.cosTable = new double[100 * 100];
  
  this.cosThread = new Thread[10];
  
  startLoop = curLoop = 0;
  
  endLoop = 100*100;
  numThreads = 10;
 }
 
 public synchronized CosTableRanges loopGetRange(){
  if (this.curLoop > this.endLoop) return null;
  CosTableRanges ret = new CosTableRanges();
  ret.start = curLoop;
  curLoop += (endLoop - startLoop)/numThreads + 1;
  ret.end = (curLoop < endLoop) ? curLoop:endLoop;
  return ret;
 }
 
 public void loopDoRange(int start, int end){
  for (int i = start; i < end; i ++){
   double cosValue = (double)Math.cos(i % 360) * Math.PI / 180.0;
   this.cosTable[i] = cosValue * (double)i / 180.0d;
  }
 }

 public void run() {
  CosTableRanges ctr;
  while ((ctr = loopGetRange()) != null){
   loopDoRange(ctr.start, ctr.end);
  }
  
 }
 
 public double[] getValues(){
  for (int i = 0; i < 100 * 100; i++){
   this.cosThread[i] = new Thread(this);
   this.cosThread[i].start() ;
  }
  for (int i = 0; i < 100 * 100; i++){
   try {
    this.cosThread[i].join() ;
   }catch (InterruptedException e){
    
   }
  }
  return this.cosTable;
 }
 
 

}
至于关于调度的策略与负载平衡等高级问题,就掠过了!:)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值