模拟死锁

本文介绍了死锁的概念,即两个或多个线程互相持有对方所需资源,导致所有线程阻塞无法运行。还给出了Java代码模拟死锁情况,通过两个线程分别尝试获取对方持有的锁,最终运行结果显示出现死锁,Thread1拿不到l2的锁,Thread2拿不到l1的锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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的锁,就产生了死锁
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值