Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package eu.ase.hpc.multith.paralel;
- public class ProgMainParalel {
- private static final int NTHREADS=4;
- public static void main(String[] args) {
- int dimVect=40_000_000;
- int[] v = new int[dimVect];
- for(int i=0;i<dimVect;i++)
- v[i]=1+i;
- int startIdx =0, stopIdx=0;
- long startTime =0, stopTime=0;
- Long[] vectSum =new Long[NTHREADS];
- //1. seq
- Long sum = new Long(0);
- startTime=System.currentTimeMillis();
- for(int i=0;i<dimVect; i++) {
- sum+=v[i];
- }
- stopTime=System.currentTimeMillis();
- System.out.println("1. Seq time = "+ (stopTime-startTime)+ ", sum = " +sum);
- //2. standart multi threading
- sum = new Long(0);
- startTime=System.currentTimeMillis();
- Thread[] vectThreads = new Thread[NTHREADS];
- MyMultiThArray[] vectRThreads= new MyMultiThArray[NTHREADS];
- for(int it=0; it<NTHREADS; it++) {
- startIdx = it* (dimVect/NTHREADS);
- stopIdx=(it+1)* (dimVect/NTHREADS)-1;
- vectSum[it]= new Long(0);
- vectRThreads[it]= new MyMultiThArray(v, startIdx, stopIdx);
- vectThreads[it]= new Thread(vectRThreads[it]);
- }
- for(int it=0;it<NTHREADS;it++) {
- vectThreads[it].start();
- }
- for(int it=0;it<NTHREADS;it++) {
- try {
- vectThreads[it].join();
- }catch(InterruptedException e) {
- e.printStackTrace();
- }
- }
- for(int it=0;it<NTHREADS;it++) {
- vectSum[it]=vectRThreads[it].getSum();
- sum+= vectSum[it];
- }
- stopTime=System.currentTimeMillis();
- System.out.println("2. Multi threading time = "+ (stopTime-startTime)+ ", sum = " +sum);
- }
- }
- package eu.ase.hpc.multith.paralel;
- public class MyMultiThArray implements Runnable {
- private int[] vinp;
- private int start;
- private int stop;
- private Long sum;
- public MyMultiThArray(int[] v, int startIdx, int stopIdx) {
- this.vinp=v;
- this.start= startIdx;
- this.stop=stopIdx;
- }
- @Override
- public void run() {
- long s=0;
- for(int idx=this.start;idx<=this.stop;idx++) {
- s+= this.vinp[idx];
- }
- this.sum=new Long(s);
- }
- public Long getSum() {
- return this.sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement