Java Tutorial/Thread/Deadlock — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 17:44, 31 мая 2010
An example of deadlock.
class A {
synchronized void foo(B b) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println("Inside A.last");
}
}
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last() {
System.out.println("Inside A.last");
}
}
class Deadlock implements Runnable {
A a = new A();
B b = new B();
Deadlock() {
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 Deadlock();
}
}
Deal with lock
public class DeadlockDemo {
public static void main(String[] args) throws Exception {
UseShared s1 = new UseShared("x");
UseShared s2 = new UseShared("y");
s1.start();
s2.start();
s1.join();
s2.join();
}
}
class UseShared extends Thread {
String s1 = "", s2 = "";
UseShared(String name) {
setName(name);
}
public void run() {
for (int i = 0; i < 100; i++) {
if (getName().equals("x"))
method1();
else
method2();
try {
Thread.sleep(1000);
} catch (Exception e) {
}
}
}
void method1() {
synchronized (s1) {
System.out.println("method1: s1");
synchronized (s2) {
System.out.println("method1: s2");
}
}
}
void method2() {
synchronized (s2) {
System.out.println("method2: s1");
synchronized (s1) {
System.out.println("method2: s2");
}
}
}
}