案例实现:
public class DeadLockTest implements Runnable {
A a = new A();
B b = new B();
public static void main(String[] args) {
DeadLockTest test = new DeadLockTest();
//执行run()方法
new Thread(test).start();
//执行init()方法
test.init();
}
@Override
public void run() {
Thread.currentThread().setName("主线程");
b.Boo(a);
}
public void init() {
Thread.currentThread().setName("分线程");
a.Aoo(b);
}
}
class A {
public synchronized void Aoo(B b) {//设置同步监视器A.class
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
b.end();//获取同步监视器B.class
}
public synchronized void end() {//设置同步监视器A.class
System.out.println("A.end");
}
}
class B {
public synchronized void Boo(A a) {//设置同步监视器B.class
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
a.end();//获取同步监视器A.class
}
public synchronized void end() {//设置同步监视器B.class
System.out.println("B.end");
}
}
- 解决方法:专门的算法、原则
- 尽量减少同步资源的定义
- 尽量避免嵌套同步