何为死锁
多线程各自持有不同的锁,并互相试图获取对方已持有的锁,导致无限等待的状况,称为死锁。比如:
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() + "已经获得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() + "已经获得o2的锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("fsf");
}
}
}
}
避免死锁
避免死锁的方法是线程获取锁的顺序要一致。
网友评论