何為死鎖
多線程各自持有不同的鎖瓜喇,并互相試圖獲取對方已持有的鎖纷纫,導(dǎo)致無限等待的狀況娩践,稱為死鎖里覆。比如:
public class DeadLock {
public static void main(String[] args) {
Object o1 = new ArrayList<>();
Object o2 = new ArrayList<>();
Thread t1 = new Thread(new MyRunnable1(o1, o2));
Thread t2 = new Thread(new MyRunnable2(o1, o2));
t1.start();
t2.start();
}
}
class MyRunnable1 implements Runnable {
final Object o1;
final Object o2;
MyRunnable1(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + "已經(jīng)獲得o1的鎖");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("fsf");
}
}
}
}
class MyRunnable2 implements Runnable {
final Object o1;
final Object o2;
MyRunnable2(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + "已經(jīng)獲得o2的鎖");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("fsf");
}
}
}
}
避免死鎖
避免死鎖的方法是線程獲取鎖的順序要一致丧荐。