1、多个线程死锁实例
(1)两个线程发生死锁
两个线程,两把锁产生死锁的代码实例
public class demo {
public static void main(String[] args) {
Object locker1 = new Object();
Object locker2 = new Object();
Thread thread1 = new Thread(()->{
synchronized (locker1){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (locker2){
System.out.println("线程1进行了加锁");
}
}
});
Thread thread2 = new Thread(()->{
synchronized (locker2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (locker1){
System.out.println("线程2进行了加锁");
}
}
});
thread1.start();
thread2.start();
}
}
运行上述代码,由于发生死锁,运行不出结果
产生死锁的原因是:
一开始,线程1拿到了locker1的琐,线程2拿到了locker2的琐
接着,线程1想拿到locker2,此时线程2还没有释放locker1;与此同时,线程2想拿locker1,而线程1还没有释放locker1
两个线程在这里发生僵持,便产生了死锁
(2)多个线程发生死锁
对于N个线程,M把锁发生死锁,可见哲学家进餐问题
2、嵌套与并行
上述多线程发生死锁一定是建立在加锁时是嵌套关系下
如果是并行关系,则不会发生死锁。如
public class demo {
public static void main(String[] args) {
Object locker1 = new Object();
Object locker2 = new Object();
Thread thread1 = new Thread(()->{
synchronized (locker1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
synchronized (locker2){
System.out.println("线程1进行了加锁");
}
});
Thread thread2 = new Thread(()->{
synchronized (locker2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
synchronized (locker1){
System.out.println("线程2进行了加锁");
}
});
thread1.start();
thread2.start();
}
}
上述代码则不会发生死锁