Bonjour,

Je suis occupé à faire des tests sur le mot clé synchronized.

Le mot clé synchronized, si j'ai bien compris, permet de s'assurer qu'un seul thread à la fois n'exécute du code se trouvant dans un bloc synchronized ou dans une méthode synchronized.

Je dispose d'un exemple et suite à des éxécutions successives du même code, les résultats obtenus sont différents.

La classe implementant Runnable :
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
 
public class Task implements Runnable {
 
	private Counter counter;
 
	public Task(Counter counter) {		
		this.counter = counter;
	}
 
	@Override
	public void run() {
		for (Long i = 0L; i < 5; i++) {						
 
				synchronized (counter) {
					counter.add(i);				
				}			
		}
	}
 
}
La classe bean :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
 
public class Counter {
	private Long count = 0L;
	private Long secondCount = 0L;
 
	public void add(Long value){		 
			count += value;
			System.out.println("The value of count is : " + count + " on " + Thread.currentThread().getName());				
	}
 
 
 
}

La classe de test:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
 
public class Test {
	public static void main(String args[]) {
 
		Counter counter = new Counter();
 
		Task threadA = new Task(counter);
		Task threadB = new Task(counter);
 
		new Thread(threadA).start();
		new Thread(threadB).start();
	}
}

Les résultats sont aléatoires, alors que les 2 threads devraient s'éxécuter les un après les autres.

Résultat 1:

The value of count is : 0 on Thread-0
The value of count is : 1 on Thread-0
The value of count is : 3 on Thread-0
The value of count is : 3 on Thread-1
The value of count is : 4 on Thread-1
The value of count is : 6 on Thread-1
The value of count is : 9 on Thread-1
The value of count is : 13 on Thread-1
The value of count is : 16 on Thread-0
The value of count is : 20 on Thread-0

Résulat 2 : (résultat désiré)

The value of count is : 0 on Thread-0
The value of count is : 1 on Thread-0
The value of count is : 3 on Thread-0
The value of count is : 6 on Thread-0
The value of count is : 10 on Thread-0
The value of count is : 10 on Thread-1
The value of count is : 11 on Thread-1
The value of count is : 13 on Thread-1
The value of count is : 16 on Thread-1
The value of count is : 20 on Thread-1

Merci d'avance pour vos réponses.