Bonjour,
bon voilà mon probleme, je tente de synchroniser deux treads, alors j'ai une class Inf qui affiche un text divisé en deux morceaux, séparé par un laps de temps,donc dans ce sens :
affichage partie 1 du texte
attente de 2 sec
affichage partie 2 du txt
donc c'est tres simple,tout se complique ici, je lance ce petit code avec deux threads distinct, donc thread a et thread b , le probleme est que quand je lance le thread a, je veux que le thread b attende que le thread a soit fini.
A priori, avec synchronized; le thread b ne peut pas acceder au thread princiapal tant que celui ci n'est pas fini, mais ça ne marche pas :
voici mon code :
et la classe Client :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56 public class Inf implements Runnable{ protected String text; protected String number; public Inf(String text){ this.text = text; } public void run(){ while(true){ try{ Thread.sleep(10); }catch(InterruptedException e){ System.out.println(e); } displayAll(); } } public synchronized void displayAll(){ displayPartOne(); try{ Thread.sleep(2000); }catch(InterruptedException e){ System.out.println(e); } displayPartTwo(); } public synchronized void displayPartOne(){ System.out.print(textPartOne()); } public synchronized void displayPartTwo(){ System.out.println(textPartTwo()); } public String textPartOne(){ String res=""; for(int i=0;i < text.length()/2;i++){ res += text.charAt(i); } return res; } public String textPartTwo(){ String res=""; for(int i=text.length()/2;i < text.length();i++){ res += text.charAt(i); } return res; } // to help me for debuging public void setNumber(String number){ this.number = number; } public String toString(){ return "thread n : "+number; } }
laffichage est le suivant :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 public class Client{ public Client() throws Exception{ Inf a = new Inf("Victor is a man"); a.setNumber("1"); Inf b = new Inf("Cleopa is a cat"); b.setNumber("2"); Thread ta = new Thread(a); Thread tb = new Thread(b); ta.start(); tb.start(); } public static void main(String [] args) throws Exception{ new Client(); } }
on voit que victor devient un chat et cleop devient un homme..Victor Cleopa is a man
is a cat
Victor Cleopa is a man
is a cat
Victor Cleopa
le probleme est clair ici, a la premiere ligne, Victor et Cleopa accede a la methode display tous les deux, alors que je pensais que Cleopa ne pouvait pas s'afficher tant que Victor n'avait pas fini..
quelqu'un peut m'aider
Partager