Bonsoir,
J ai un programme qui utilise des threads (de meme classe).
Pour des raison des clareté, j execute les threads dans des terminaux différents. Or je n arrive pas a partager des variables (j utilise pourtant les singletons).
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84 ///////////////////////////////// fichier A.java ///////////////////////////////// class A implements runnable { int num; Thread thread; public A() { Singleton.incrNum(); } public synchronized void initNum() { num = Singleton.getInstance(); Singleton.incrNum(); } public void run() { try { isReady(); } catch (InterruptedException e) { e.printStackTrace(); } // action a faire. } public synchronized void isReady() throws InterruptedException { if (num != 1) { wait(); } else { notifyAll(); } } public static void main(String[] args) { A a = new A(); a.thread.start(); } } ////////////////////////////// fichier Singleton.java ////////////////////////////// class Singleton { private static Singleton instance; private int num; private int[] tab; private Singleton(){ tab = new int[2]; num = 0; } public synchronized static Singleton getInstance() { if (instance == null) return instance = new Singleton(); return instance; } public int getNum() { return num; } public int getTab(int indice) { return tab[indice]; } public void setTab(int indice, int val) { tabPorts[indice] = val; } public synchronized void incrNum() { num++; } }
En gros voila ce que je voudrais que ca fasse. J ouvre 2 terminaux et je lance un thread A dans chaque terminal.
Tant que le 2nd thread n'est pas créé, le premier attend. Ensuite les treads peuvent continuer.
Or moi j ai toujour Singleton.getInstance().getNum() = 1; // apres le initNum() (de plus jep ense que le thread endormi ne sera pas reveillé avec le notifyall()).
Si quelqu un a une solution à ce problème. Merci.
Partager