Exemplo de deadlock
Revisión del 17:31 26 oct 2021 de Joselv (discusión | contribuciones) (Página creada con « package DeadLock2; //Un exemplo deadlock. class A { synchronized void foo(B b) { String name = Thread.currentThread().getName(); System.out.println(name + " de…»)
package DeadLock2;
//Un exemplo deadlock. class A {
synchronized void foo(B b) {
String name = Thread.currentThread().getName();
System.out.println(name + " dentro A.foo");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("A Interrupted");
}
System.out.println(name + " Intentando chamar a B.last()"); b.last(); }
synchronized void last() {
System.out.println("Dentro de A.last");
}
}
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " dentro B.bar");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " Intentando chamar a a A.last()"); a.last(); }
synchronized void last() {
System.out.println("Dentro de A.last");
}
}
class Deadlock2 implements Runnable {
A a = new A(); B b = new B();
Deadlock2() {
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
}
public void run() {
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
}
public static void main(String args[]) {
new Deadlock2();
}
}