Olá pessoal!
Estou estudando concorrência pelo[color=blue] tutorial da sun[/color], e não sei se entendi direito o exemplo que eles colocam na parte de deadlock. Aqui vai a classe de exemplo deles, um pouco alterada por mim.
01 /**
02 * @author Sun
03 */
04 package com.sun.tutorial.concurrency.liveness;
05
06 import br.com.autbank.tech.util.time.Pause;
07
08 public class Deadlock {
09 static class Friend {
10 private final String name;
11
12 public Friend(String name) {
13 this.name = name;
14 }
15
16 public String getName() {
17 return this.name;
18 }
19
20 public synchronized void bow(Friend bower) {
21 System.out.format(
22 "%s: %s has bowed to me!%n",
23 this.name,
24 bower.getName()
25 );
26 bower.bowBack(this);
27 }
28
29 public synchronized void bowBack(Friend bower) {
30 System.out.format(
31 "%s: %s has bowed back to me!%n",
32 this.name,
33 bower.getName()
34 );
35 }
36 }
37
38 public static void main(String[] args) {
39 final Friend alphonse = new Friend("Alphonse");
40 final Friend gaston = new Friend("Gaston");
41 while(true) {
42 Thread
43 t1 = new Thread(
44 new Runnable() {
45 public void run() {
46 alphonse.bow(gaston);
47 System.out.println();
48 }
49 }
50 ),
51 t2 = new Thread(
52 new Runnable() {
53 public void run() {
54 gaston.bow(alphonse);
55 System.out.println();
56 }
57 }
58 )
59 ;
60 t1.start();
61 t2.start();
62 Pause.zzz(5);
63 if(t1.isAlive() && t2.isAlive()) {
64 System.out.println(
65 "OH MY GOD! It seems like I'm entering in a deadlock..."
66 );
67 Pause.zzz(1000);
68 if(t1.isAlive() && t2.isAlive()) {
69 System.err.println("Yes... I'm in a deadlock indeed... Bye!!!");
70 System.exit(0);
71 }else
72 System.out.println(
73 "Not a deadlock... Just my imagination... So, contiue then!"
74 );
75 }
76 System.out.println();
77 }
78 }
79 }
Ao executar esse programa, mais cedo ou mais tarde ele entra em deadlock. Eu gostaria que vocês confirmasse se eu realmente entendi como funciona o lock obtido pela thread quando se entra em um método sincronizado: Quando a thread t invoca um método sincronizado de um objeto obj e consegue adiquirir o intrinsic lock deste objeto, nenhuma outra thread conseguirá acessar membro algum de obj, até que t libere o intrinsic lock de obj.
É isso, ou eu comi bola?