线程死锁发生在争夺资源,互相需要 对方资源且又相互占用对方资源的情况。
假设线程T1占用o1资源,而线程T2占用o2资源,线程T1需要o2资源才能释放当前所占用的o1资源,而线程T2需要o1资源才能释放占用的o2资源,此时产生了死锁。

释放锁条件:
1、当前线程的同步方法、同步代码块执行结束
2、当前线程在同步代码块、同步方法中遇到break. return
3、当前线程在同步代码块、同步方法中出现了未处理的Error或Exception,导致异常结束
4、当前线程在同步代码块、同步方法中执行了线程对象的wait0方法,当前线程暂停,并释
放锁
- public class DeadLock {
- public static void main(String[] args) {
- Thread thread1 = new Thread(new DeadLockDemo(true));
- Thread thread2 = new Thread(new DeadLockDemo(false));
- thread1.start();
- thread2.start();
- }
- }
-
-
- class DeadLockDemo implements Runnable {
-
- static Object o1 = new Object();
- static Object o2 = new Object();
- boolean flag;
-
- public DeadLockDemo(boolean flag) {
- this.flag = flag;
- }
-
- @Override
- public void run() {
- if (flag) {
- synchronized (o1) {
- System.out.println(Thread.currentThread().getName() + "线程进入o1");
- synchronized (o2) {
- System.out.println(Thread.currentThread().getName() + "线程进入o2");
- }
- }
- } else {
- synchronized (o2) {
- System.out.println(Thread.currentThread().getName() + "线程进入o2");
- synchronized (o1) {
- System.out.println(Thread.currentThread().getName() + "线程进入o1");
- }
- }
- }
- }
- }