/**
* @author liangjun
* @descriptionTODO
* alphonse gaston 两个对象相互等着对方释放锁,线程阻塞,造成死锁
*/
public class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower){
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friendbower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
/**
* @author liangjun
* @descriptionTODO
* 1.同一对象多线程分别调用method1 method2时,
* 2.ThreadA获得锁lock_1,ThreadB获得lock_2,
* 3.ThreadA继续执行获得lock_2时,或者ThreadB继续执行获得lock_1时,lock_2/lock_1分别被对方占有,
* 4.ThreadA/ThreadB线程阻塞,造成死锁现象
*
*/
class Deadlocker {
int field_1;
private Objectlock_1 = newint[1];
int field_2;
private Objectlock_2 = newint[1];
public void method1(int value) {
synchronized (lock_1) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程:" + Thread.currentThread().getName());
synchronized (lock_2) {
field_1 = 0;
field_2 = 0;
System.out.println("method1");
}
}
}
public void method2(int value) {
synchronized (lock_2) {
System.out.println("当前线程:" + Thread.currentThread().getName());
synchronized (lock_1) {
field_1 = 0;
field_2 = 0;
System.out.println("method2");
}
}
}
public static void main(String args[]) {
final Deadlocker dl =new Deadlocker();
new Thread(new Runnable() {
@Override
public void run() {
dl.method1(0);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
dl.method2(1);
}
}).start();
}
}
/**
* 解决方案:让所有的线程按照同样的顺序获得一组锁
* 将多个锁组成一组并放到同一个锁下
*/