死锁的Demo,产生条件
多线程
多线程的出现使信息的传输/计算更加流畅
但是也出现了一些问题
多个线程对同一资源进行操作
本身就是一个很谨慎的过程
并发三要素
所以就有了并发三要素
- 原子性:事务的概念
- 可见性:对其他线程可见
- 有序性:有顺序执行
死锁四个必要
以及死锁产生的四个必要条件
- 互斥
- 请求和保持
- 循环等待
- 不可抢占
如果不考虑这些
资源被多个线程争抢,各自进程争抢资源互相阻塞,导致永久停滞
Demo - 死锁
public class DeadLockOne {
public static void main(String[] args) throws InterruptedException {
final Object a = new Object();
final Object b = new Object();
Thread threadA = new Thread(new Runnable() {
public void run() {
synchronized (a) {
try {
System.out.println("Now in threadA-locka");
Thread.sleep(100);
synchronized (b) {
System.out.println("Now in threadA-lockb");
}
} catch (Exception e) {
System.out.println("Exception "+ e);
}
}
}
});
Thread threadB = new Thread(new Runnable() {
public void run() {
synchronized (b) {
try {
System.out.println("Now in threadB-lockb");
Thread.sleep(100l);
synchronized (a) {
System.out.println("Now i in threadB-locka");
}
} catch (Exception e) {
System.out.println("Exception "+ e);
}
}
}
});
threadA.start();
threadB.start();
}
}
这里的synchronized - a,b 都是基本同步的,但是
Object A(OA)和Object B(OB)随后就被锁住
第一个TA中,想继续去拿到OB ---- OB在TB中被锁住了,
第二个TB中,想继续去拿到OA ---- OA在TA中被锁住了
于是,资源被阻塞,线程停滞
Demo - 处理死锁
想要解决,就得破坏死锁四大前提
```java
public class DeadLockOne {
public static void main(String[] args) throws InterruptedException {
final Object a = new Object();
final Object b = new Object();
Thread threadA = new Thread(new Runnable() {
public void run() {
synchronized (a) {
try {
System.out.println("now i in threadA-locka");
Thread.sleep(3001);
synchronized (b) {
System.out.println("now i in threadA-lockb");
}
} catch (Exception e) {
System.out.println("Exception "+ e);
}
}
}
});
Thread threadB = new Thread(new Runnable() {
public void run() {
synchronized (a) {
try {
System.out.println("now i in threadB-lockb");
Thread.sleep(300l);
synchronized (b) {
System.out.println("now i in threadB-locka");
}
} catch (Exception e) {
System.out.println("Exception "+ e);
}
}
}
});
threadA.start();
threadB.start();
}
}
这里threadA先start,开始锁a,线程暂停,
threadB想要拿到ObjectA,但是OA锁住
3s后释放,OB打印
System.out.println("now i in threadA-lockb");
TB中的OA同时打印
System.out.println("now i in threadB-lockb");
随后,TB中的OB打印
System.out.println("now i in threadB-locka");