Bonjour,
En fonction de l'objet qui appel la fonction synchronized, je n'obtient pas les même choses. Qu'est ce que ça change qu un, objet appel synchronized à la place d'un autre ?
Merci d'avance pour votre aide.
Voila un exemple complet :
Là on est bloqué. si on remplace a.synchro et b. synchro par this.synchro, on n'est pas bloqué mais c'est la même chose que si le thread s’exécutait séquentiellement.Code:
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 def thread(body: =>Unit): Thread = { val t = new Thread { override def run() = body } t.start() t } object SynchronizedDeadlock extends App { class Account(val name: String, var money: Int) def send(a: Account, b: Account, n: Int) = b.synchronized { print("1"); println(Thread.currentThread.getName) a.synchronized { print("2"); println(Thread.currentThread.getName) a.money -= n b.money += n } } val a = new Account("Jill", 1000) val b = new Account("Jack", 2000) println(Thread.currentThread.getName) val t1 = thread { for (i <- 0 until 30) send(a, b, 1) } val t2 = thread { for (i <- 0 until 30) send(b, a, 1) } t1.join() t2.join() log(s"a = ${a.money}, b = ${b.money}")
