# TP 1 -- Théorie de la concurrence ###### tags `TD` `M1 S1` `concurrence` [Sommaire](/bAJa0viuQp68XN74HxpVJA) > [time= 22 sept 2020] [TOC] ## Exercice 1 ### Enoncé  ### Réponse ```java= import java.io.*; class Ex1 { public static void write_num(String name) { try { Writer wr = new FileWriter(name); DataOutputStream stream = new DataOutputStream( new FileOutputStream(name)); for (int k = 1; k < 100; k++) { int num = (int) (Math.random() * 50); wr.write(num + "\n"); } wr.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { Ex1.write_num("file_ex1.txt"); } } ``` ## Exercice 2 ### Enoncé  ### Réponse ```java= public class Ex2 { static int count = 5; public static int average_sum(String path) { Result results = new Result(count); SommeThread[] threads = new SommeThread[count]; for (int i = 0; i < count; i++) { threads[i] = new SommeThread(path, i, results); threads[i].start(); } int res = 0; for (int i = 0; i < count; i++) { try { threads[i].join(); int cur_sum = results.tab[i]; System.out.printf("thread %d: %d\n", threads[i].id, cur_sum); res += cur_sum; } catch (InterruptedException e) { e.printStackTrace(); } } return res / count; } public static void main(String[] args) { String file_name = "file_ex1.txt"; int result = Ex2.average_sum(file_name); System.out.println("result: " + result); } } ``` ```java=+ public class Resultat { public int[] tab; public Resultat(int size) { tab = new int[size]; } } ``` ```java=+ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class SommeThread extends Thread { public final String path; public final int id; Result result; public SommeThread(String path, int id, Result result) { this.path = path; this.id = id; this.result = result; } public void run() { try { FileReader file = new FileReader(new File(path)); BufferedReader br = new BufferedReader(file); String line; int sum = 0; while ((line = br.readLine()) != null) { sum += Integer.parseInt(line); } result.tab[id] = sum; } catch (IOException e) { e.printStackTrace(); } } } ``` ## Exercice 3 ### Enoncé   ### Réponse #### 1) Non #### 2) On peut récrire sur des valeurs. #### 3) on modifie la ligne `echange(a, b)` pour mettre `synchonized(res){exchange(a, b)}` ## Exercice 4 ### Enoncé   ### Réponse #### 1) Non #### 2) On peut récrire sur des valeurs. #### 3) on ajoute un`synchronized` à la méthode `resultatbis.echange()` ## Exercice 5 ### Enoncé  ### Réponse
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up