package compteurs; public class CompteurVarPartagee implements Runnable { /** * Un compteur qui compte jusqu'à 10 en faisant une pose * aléatoire entre 2 nombres, et qui démontre une facon de * partager une variable entre plusieurs threads (ici, par passage * de référence vers un objet, au moment de la construction de chaque thread) * Mais attention, chaque thread reçoit une copie de la ref. vers l'objet * Si un thread modifie cette référence pour pointer vers un autre objet * cela n'a pas d'impact pour les autres threads * Ce qui est délicat, c'est de mettre au point un scénario * dans lequel, une modification faite par un thread est * visible par les autres threads. Par exemple, on a choisi * de modifier la chaîne de car. en l'inversant **/ private String nom; private int max; static private int position; public CompteurVarPartagee(String nom, int max) { this.nom = nom; this.max = max; } public CompteurVarPartagee(String nom) { this(nom, 10); } public String getNom() { return nom; } public int getMax() { return max; } public void run() { /*if (getNom() == "Pierre") { max = this.getMax() * 10; } */ System.out.println(getNom()+" incrémente le nombre : " + this.getMax()); for (int i = 1; i <= max; i++) { try { Thread.sleep((int) (Math.random() * 5000)); } catch (InterruptedException e) { System.err.println(getNom() + " a ete interrompu."); } System.out.println(getNom() + " : " + i); } position++; System.out.println("*** " + getNom() + " a termine en position " + position); } public static void main(String[] args) { String message="Coucou, je suis une chaine partagee"; StringBuffer sb=new StringBuffer(message); CompteurVarPartagee[] compteurs = { new CompteurVarPartagee("Toto",10), new CompteurVarPartagee("Bibi",10), new CompteurVarPartagee("Robert",10), new CompteurVarPartagee("Pierre",10) }; for (int i = 0; i < compteurs.length; i++) { new Thread(compteurs[i]).start(); } } }