In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
这篇文章主要讲解了"java死锁发生的必要条件",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"java死锁发生的必要条件"吧!
死锁的必要条件
互斥条件
请求和保持条件
不剥夺条件
环路等待条件
/** * 一个简单的死锁类 * 当DeadLock的对象flag==1时(d1), 先锁定o1,睡眠500毫秒 * 而d1在睡眠的时候留一个flag=0的对象(d2)线程启动,先锁定o2,睡眠500毫秒 * d1睡眠结束后需要锁定o2才能继续执行,而此时o2已经被d2锁定; * d2睡眠结束后需要锁定o1才能继续执行,而此时o1已经被d1锁定; * d1,d2相互等待,都需要得到对方锁定改的资源才能继续执行,从而死锁 */@Slf4jpublic class DeadLock implements Runnable { public int flag = 1; //静态资源是类的所有对象共享的 private static Object o1 = new Object(), o2 = new Object(); @Override public void run() { log.info("flag:{}", flag); if(flag == 1){ synchronized (o1) { try{ Thread.sleep(500); } catch (Exception e){ e.printStackTrace(); } synchronized (o2) { log.info("1"); } } } if (flag == 0) { synchronized (o2) { try { Thread.sleep(500); }catch (Exception e){ e.printStackTrace(); } synchronized (o1) { log.info("0"); } } } } public static void main(String[] args) { DeadLock d1 = new DeadLock(); DeadLock d2 = new DeadLock(); d1.flag = 1; d2.flag = 0; //d1,d2都处于可执行状态,但JVM线程调度先执行哪个线程是不确定的。 //d2的run()可能在d1的run()之前执行 new Thread(d1).start(); new Thread(d2).start(); }}
如何避免死锁:
注意加锁顺序
加锁时间限制,可以使用ReentrantLock可以设置获取所得给定时间,超过一定时间就释放自己占用的锁
感谢各位的阅读,以上就是"java死锁发生的必要条件"的内容了,经过本文的学习后,相信大家对java死锁发生的必要条件这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.