| |
10. 16. 2. 死锁处理 |
|
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");
}
}
}
}
|
|
10. 16. 死锁 | | 10. 16. 1. | 一个死锁例子。 | | | | 10. 16. 2. | 死锁处理 | | |
|