Facebook
From Capacious Motmot, 6 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 232
  1. package com.company;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.concurrent.*;
  6.  
  7. public class Main2 {
  8.     private static final int NTHREADS = 10;
  9.     private static final int NTASKS = 100;
  10.  
  11.     public static void main(String[] args) throws ExecutionException, InterruptedException {
  12.         double xp = 0, xk=Math.PI, dl = ((Math.PI-0)/NTASKS), dx = 0.00001;
  13.  
  14.         Counter counter = new Counter();
  15.         ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);
  16.         List<Future<Double>> list = new ArrayList<Future<Double>>();
  17.  
  18.         for(int i=0;i<NTASKS;i++){
  19.             double a = xp+i*dl;
  20.             double b = xp+(i+1)*dl;
  21.  
  22.             Callable<Double> callable = new Calka_callable(a, b, dx);
  23.             Future<Double> future = executor.submit(callable);
  24.             list.add(future);
  25.         }
  26.         double sum = 0;
  27.  
  28.         for(Future<Double> future_double : list){
  29.             try{
  30.                 sum+=future_double.get();
  31.             }catch (InterruptedException|ExecutionException e){
  32.                 e.printStackTrace();
  33.             }
  34.         }
  35.  
  36.         System.out.println("Suma dla puli watkow : " + sum);
  37.         // This will make the executor accept no new threads
  38.         // and finish all existing threads in the queue
  39.         executor.shutdown();
  40.  
  41.         // Wait until all threads finish
  42.         while (!executor.isTerminated()) {
  43.         }
  44.  
  45.         System.out.println("Finished all threads");
  46.     }
  47. }
  48.