多个线程同步时,如果获得的锁的顺序不一致,可能会导致线程相互等待的情况,称为死锁。
一个简单死锁的代码:
class ThreadDeadLock1 implements Runnable {
Object o1;
Object o2;
public ThreadDeadLock1(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o1){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2){
}
}
}
}
class ThreadDeadLock2 implements Runnable {
Object o1;
Object o2;
public ThreadDeadLock2(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o2){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1){
}
}
}
}
public class DeadLock {
public static void main(String[] args) {
Object o1 = new Object();
Object o2 = new Object();
Thread t1 = new Thread(new ThreadDeadLock1(o1, o2));
Thread t2 = new Thread(new ThreadDeadLock2(o2, o1));
t1.start();
t2.start();
}
}