aula05ThreadsMultiplasParalelas

class ParallelPi extends Thread {
    private int myId, nThreads, nIntervals, myIntervals;
    private double dX;
    private double myResult;

    public ParallelPi(int myId, int nThreads, int nIntervals) {
        this.myId = myId;
        this.nThreads = nThreads;
        this.nIntervals = nIntervals;
        //calculo do uso da largura
        dX = 1.0 / (double) nIntervals;
        myResult = 0;
        myIntervals = 0;
    }

    public double getMyResult() {
        return myResult;
    }

    public int getMyIntervals() {
        return myIntervals;
    }

    //o que a thread executa
    @Override
    public void run() {
        double i, xi;
        myResult = 0;

        //verificações relacionadas com as threadas e ids das threads
        if (nIntervals < 1 || nThreads < 1 || myId < 1 || myId > nThreads) {
            return;
        }
        for (i = myId - 1; i < nIntervals; i += nThreads) {
            xi = dX * (i + 0.5);
            myResult += (4.0 / (1.0 + xi * xi));
            myIntervals++;
        }
        myResult *= dX;
    }
}

public class aula05ThreadsMultiplasParalelas {
    public static void main(String[] args) throws InterruptedException {
        ParallelPi[] t; //Working threads
        int i, nThreads;
        long nIntervals;
        double pi = 0.0;
        if (args.length != 2) {
            System.out.println("Sintaxe: java ParallelPi <número de intervalos > < número de threads>");
            return;
        }
        nIntervals = Integer.parseInt(args[0]);
        nThreads = Integer.parseInt(args[1]);
        t = new ParallelPi[nThreads];
        for (i = 0; i < nThreads; i++) {
            t[i] = new ParallelPi(i + 1, nThreads, (int) nIntervals);
            t[i].start();
        }

        pi = 0;
        for (i = 0; i < nThreads; i++) {
            t[i].join();
            pi += t[i].getMyResult();
        }
        System.out.println("Valor aproximado de pi: " + pi);
    } //main
} //class ParallelPi
Tags : ,

0 thoughts on “aula05ThreadsMultiplasParalelas”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.