Created
February 12, 2018 08:33
-
-
Save jstefanelli/c46d5159d71a694c746a5e5cb820bcb9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.*; | |
| public class Sommatore{ | |
| public class Somma{ | |
| public int a, b, result; | |
| public Somma(int a, int b){ | |
| this.a = a; | |
| this.b = b; | |
| result = 0; | |
| } | |
| } | |
| private ArrayList<Somma> somme = new ArrayList<>(); | |
| private int index = 0; | |
| public void addSomma(int a, int b){ | |
| synchronized(somme){ | |
| somme.add(new Somma(a, b)); | |
| } | |
| } | |
| private void threadRunner(){ | |
| while(true){ | |
| Somma s; | |
| synchronized(somme){ | |
| if(index >= somme.size()) | |
| return; | |
| s = somme.get(index++); | |
| } | |
| s.result = s.a + s.b; | |
| } | |
| } | |
| public void calcola(int numThreads){ | |
| Thread[] t = new Thread[numThreads]; | |
| for(int i = 0; i < numThreads; i++){ | |
| t[i] = new Thread(new Runnable(){ | |
| public void run(){ | |
| threadRunner(); | |
| } | |
| }); | |
| } | |
| for(int i = 0; i < numThreads; i++){ | |
| t[i].start(); | |
| } | |
| for(int i = 0; i < numThreads; i++){ | |
| try{ | |
| t[i].join(); | |
| }catch(InterruptedException ex){ | |
| } | |
| } | |
| } | |
| public ArrayList<Somma> getSomme(){ | |
| return somme; | |
| } | |
| //Uso: java sommatore <numero interi> <numero thread> | |
| public static void main(String[] args){ | |
| if(args.length < 2){ | |
| System.out.println("Usage: java sommatore <num integers> <num threads>"); | |
| return; | |
| } | |
| Sommatore sm = new Sommatore(); | |
| Random r = new Random(); | |
| int ints = Integer.parseInt(args[0]); | |
| int threads = Integer.parseInt(args[1]); | |
| for(int i = 0; i < ints; i++){ | |
| sm.addSomma(r.nextInt(), r.nextInt()); | |
| } | |
| sm.calcola(threads); | |
| ArrayList<Somma> somme = sm.getSomme(); | |
| for(Somma s : somme){ | |
| System.out.println("Somma: " + s.a + " + " + s.b + " = " + s.result); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment