博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java写一个简单的死锁程序
阅读量:3953 次
发布时间:2019-05-24

本文共 3135 字,大约阅读时间需要 10 分钟。

Java死锁程序

public class DeadLock {
public static void main(String[] args) {
new Thread(() -> {
try {
System.out.println("thread1 开始运行"); synchronized (DeadLock.class) {
System.out.println("thread1 获取 DeadLock.class对象 锁'"); Thread.sleep(1000); // 让出CPU,让thread2先获得Object.class锁 synchronized (Object.class) {
System.out.println("thread1 获取 Object.class对象 锁"); } } } catch (Exception e) {
e.printStackTrace(); } System.out.println("thread1 结束!!"); }).start(); new Thread(() -> {
try {
System.out.println("thread2 开始运行"); synchronized (Object.class) {
System.out.println("thread2 获取 Object.class对象 锁"); Thread.sleep(1000); // 让出CPU,让thread1先获得DeadLock.class锁 synchronized (DeadLock.class) {
System.out.println("thread2 获取 DeadLock.class对象 锁'"); } } } catch (Exception e) {
e.printStackTrace(); } System.out.println("thread2 结束!!"); }).start(); }}

运行结果:

thread1 开始运行thread1 获取 DeadLock.class对象 锁'thread2 开始运行thread2 获取 Object.class对象 锁

为什么要有sleep?

因为,sleep可以让当前线程让出CPU,让另一个线程运行。

比如线程1 sleep的时候,它已经获得了DeadLock锁,它下一步要获得Object锁。
这时让出cpu,可以让线程2先获得Object的锁。这样线程1就得不到了。同时线程2还请求线程1得到的DeadLock锁,显然得不到!
造成了循环等待!

去掉线程里的两个sleep语句,死锁可能就没有了!(注意,只是可能没有)

public class DeadLock {
public static void main(String[] args) {
new Thread(() -> {
try {
System.out.println("thread1 开始运行"); synchronized (DeadLock.class) {
System.out.println("thread1 获取 DeadLock.class对象 锁'"); // Thread.sleep(1000); // 让出CPU,让thread2先获得Object.class锁 synchronized (Object.class) {
System.out.println("thread1 获取 Object.class对象 锁"); } } } catch (Exception e) {
e.printStackTrace(); } System.out.println("thread1 结束!!"); }).start(); new Thread(() -> {
try {
System.out.println("thread2 开始运行"); synchronized (Object.class) {
System.out.println("thread2 获取 Object.class对象 锁"); // Thread.sleep(1000); // 让出CPU,让thread1先获得DeadLock.class锁 synchronized (DeadLock.class) {
System.out.println("thread2 获取 DeadLock.class对象 锁'"); } } } catch (Exception e) {
e.printStackTrace(); } System.out.println("thread2 结束!!"); }).start(); }}

某一种运行结果:

thread1 开始运行thread2 开始运行thread2 获取 Object.class对象 锁thread2 获取 DeadLock.class对象 锁'thread2 结束!! // 线程2一次性执行完,释放所有锁!thread1 获取 DeadLock.class对象 锁'thread1 获取 Object.class对象 锁thread1 结束!!

转载地址:http://ljkzi.baihongyu.com/

你可能感兴趣的文章
如何在SwaggerAPI中添加统一授权认证
查看>>
多线程
查看>>
【Linux】Centos7 常用命令
查看>>
【Redis】Centos7下安装Redis
查看>>
【Redis】Centos7下搭建Redis集群
查看>>
【Redis】Centos7下搭建Redis集群——哨兵模式
查看>>
【Linux】本地ping不同VM虚拟机
查看>>
【SpringCloud】Hystrix
查看>>
快速阅读——《认知篇》
查看>>
【Asp.net】基本概念
查看>>
【Asp.net】Web服务器控件
查看>>
【Asp.net】内置对象
查看>>
C语言数据类型笔记 by STP
查看>>
C语言指针笔记 by STP
查看>>
CoreLocation笔记 by STP
查看>>
Application Transport Security has blocked a cleartext HTTP (http://) 解决方案
查看>>
The identity used to sign the executable is no longer valid.解决方案
查看>>
Xcode增加pch文件
查看>>
CocoaPods安装和使用笔记 by STP
查看>>
Could not find developer disk image-解决方案
查看>>