死锁:是指有两个或者多个线程互相持有对方需要的资源,导致涉及到的所有线程都处于阻塞状态,无法继续运行。

import java.util.ArrayList;
import java.util.List;

public class DeadTest {
    private static List<String> l1 = new ArrayList<>();
    private static List<String> l2 = new ArrayList<>();
    public static void main(String[] args) {
        // Thread1
        new Thread(()->{
            try {
                System.out.println("Thread1 starting.....");
                while(true){
                    synchronized(DeadTest.l1){
                        System.out.println("Thread1 获取了 l1的锁");
                        Thread.sleep(1000);
                        System.out.println("Thread1 想获取 l2的锁");
                        synchronized(DeadTest.l2){
                            System.out.println("Thread1 拿到了l2的锁");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        // Thread1
        new Thread(()->{
            try {
                System.out.println("Thread2 starting.....");
                while(true){
                    synchronized(DeadTest.l2){
                        System.out.println("Thread2 获取了 l2的锁");
                        Thread.sleep(1000);
                        System.out.println("Thread2 想获取 l1的锁");
                        synchronized(DeadTest.l1){
                            System.out.println("Thread2 拿到了l1的锁");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}

运行结果如下:Thread1永远拿不到l2的锁,Thread2永远拿不到l1的锁,就产生了死锁模拟死锁
 

 

相关文章:

  • 2022-01-09
  • 2022-03-07
  • 2021-08-30
  • 2022-12-23
  • 2021-06-21
  • 2021-09-23
  • 2021-10-29
  • 2021-12-07
猜你喜欢
  • 2021-12-10
  • 2022-01-04
  • 2021-07-03
  • 2022-12-23
相关资源
相似解决方案